For the business layer of the program's fatal error, we have been the practice is to directly throw the specified exception, let the program go to the end, this is true, because if a business has a fatal blocking problem, there is no need to go up a layer of return, but then there is a problem, the direct throw exception, means that the server directly 500, the front-end how to display, or if you are the API service, if the front-end return, if it is 500, then directly hung up, haha!
The following is an optimized global exception capture code (non-API) in an MVC environment
<summary>///Global exception capture///</summary> public class Globalexceptionfilterattribute:handleerror Attribute {public override void Onexception (Exceptioncontext context) {Jsonresult response = New Jsonresult () {jsonrequestbehavior = jsonrequestbehavior.allowget}; if (context. Exception is ArgumentException) {var Exception = (ArgumentException) context. Exception; Response. Data = new {StatusCode = System.Net.HttpStatusCode.InternalServerError, ErrorCode = "Up", message = exception. Message,}; } else if (context. Exception is Exception) {var Exception = (Exception) context. Exception; Response. Data = new {StatusCode = System.Net.HttpStatusCode.InternalServerError, ErrorCode = "", message = exception. Message,}; } else {response. Data = new {StatusCode = System.Net.HttpStatusCode.InternalServerError, ErrorCode = "OK", message = "Other exception",}; } context. Result = response; Context. Exceptionhandled = true; Context. HttpContext.Response.Clear (); Context. HttpContext.Response.TrySkipIisCustomErrors = true; } }
If there is a problem with the business layer, throw it directly.
if (id = = 0) throw new ArgumentException ("ID cannot be 0"); if (ID < 0) throw new ArgumentException ("ID cannot be negative");
Then after the page, deliberately let it throw an exception, we look at the results of the page response
In fact, for the server, it is 200, normal return, and for the non-business module, its state is a 500, hehe, this should be clear.
Thank you for reading!
Fall in love with the mvc~ business layer intentionally throws an exception, the global exception captures it and returns it as a format