In general development you will encounter a lot of situations that require custom throw exceptions, but the thrown custom exception needs to be separated from other exceptions (null reference, array out of bounds, server crashes, etc.) and can be encapsulated in a simple code as follows.
Public Static voidThrowException (stringexceptionmessage) {Exception ex=NewException (exceptionmessage); Ex. data[0] =1; Throwex; } Public Static voidExceptioncreate (refResultdata Revalue, Exception ex) { if(ex. data!=NULL&&ex. Data.count>0&& (int) ex. data[0] ==1) Revalue.message=Ex. Message; ElseRevalue.message="system error, please contact the administrator! "; Revalue.success=false; }
Where Resultdata is also a simple package that records the classes that return JSON:
Public classResultdata {/// <summary> ///is successful/// </summary> Public BOOLSuccess {Get;Set; } /// <summary> ///Service-side messages/// </summary> Public stringMessage {Get;Set; } /// <summary> ///Error code/// </summary> Public LongCode {Get;Set; } /// <summary> ///Data Entity/// </summary> Public DynamicData {Get;Set; } /// <summary> ///total data (for paging)/// </summary> Public intTotaldatas {Get;Set; } PublicResultdata () {Success=true; } } Public classResultdata<t> { /// <summary> ///is successful/// </summary> Public BOOLSuccess {Get;Set; } /// <summary> ///Service-side messages/// </summary> Public stringMessage {Get;Set; } /// <summary> ///Error code/// </summary> Public LongCode {Get;Set; } /// <summary> ///Data Entity/// </summary> PublicT Data {Get;Set; } /// <summary> ///total data (for paging)/// </summary> Public intTotaldatas {Get;Set; } PublicResultdata () {Success=true; } }
The next step is to use the method:
PublicActionResult haspermission () {Resultdata revalue=NewResultdata (); Try { //throws an exception if the specified condition is not met if(false) sitecommon.throwexception ("Custom exception information, such as: Insufficient permissions"); } Catch(Exception ex) {sitecommon.exceptioncreate (refRevalue,ex); } returnJson (revalue); }
Simple Exception Encapsulation