Implementation Upgrade of Custom Error Page in. net

  • 2021-10-25 06:26:31
  • OfStack

Problem description:

In the last blog post ". net Custom Error Page Implementation", how to implement custom error page implementation in. net has been introduced (those who need it can go to the last blog post to learn about it). Simply setting according to the previous blog post can realize the exception custom jump of all requests, but this will cause another problem: when the request is submitted through ajax submission request acquisition interface, if there is an unhandled exception, it will be redirected to the custom error page.

For ajax request or interface request, returning a redirect page in this way is obviously not very friendly. For this problem, the following is a brief summary of my own ideas and solutions. Of course, it is not scientific and reasonable, so I also hope to have Daniel Duoduo's guidance.

To solve the problem, I think of 2:

Solution 1:

Separated from the physical structure, Strictly divide the web project into two projects (of course, continue to subdivide as needed): Website (only website page resources and other contents), interface (including all data logical processing of website, and data request interaction of page is directly interacted with interface (js technology)), Only the website project sets the custom error page mode according to the previous blog post, This can solve the problem and the project will be clearer. There are also many companies' projects that follow this method (especially webApp), but in actual projects, many projects do not achieve this strict distinction, so the following Solution 2 will introduce a more general method

Solution 2:

The solution is to combine the implementation of the last blog post. net custom error page with the three ways of catching global unhandled exceptions in the last blog post. net, and strictly agree in actual development (all requests except url address requests are interacted through post requests). When an exception is caught, if it is an post request, handle the exception and clear it. The specific steps are as follows:

Step 1: Define a request processing result data MODEL with the following code:


/// <summary>
 ///  Request result MRequestResult
 /// </summary>
 public class MRequestResult
 {
 /// <summary>
 ///  Request result code (yes 1 Enumerated values) 
 /// </summary>
 private RequestResultCodeEnum requestResultCode;

 /// <summary>
 ///  The specific return value of the processing result 
 /// </summary>
 private object resultValue;

 /// <summary>
 ///  Request result code (yes 1 Enumerated values) 
 /// </summary>
 public RequestResultCodeEnum RequestResultCode
 {
  get
  {
  return this.requestResultCode;
  }

  set
  {
  this.requestResultCode = value;
  }
 }

 /// <summary>
 ///  The specific return value of the processing result 
 /// </summary>
 public object ResultValue
 {
  get
  {
  return this.resultValue;
  }

  set
  {
  this.resultValue = value;
  }
 }
 }


 /// <summary>
 ///  Request result enumeration value ()
 /// </summary>
 public enum RequestResultCodeEnum
 {
 /// <summary>
 ///  Request succeeded 
 /// </summary>
 Success = 1,

 /// <summary>
 ///  Request failed 
 /// </summary>
 Fail = -1,
 }

Step 2: Follow the steps of the previous blog post:. net Custom Error Page Implementation, and configure the configuration operations related to the custom error page

Step 3: Follow the steps of the previous blog post:. net to catch global unhandled exceptions in three ways to set up global exceptions for handling related operations

Step 4: In catching global unhandled exceptions, add exception handling filter for post request (directly input encapsulated). The specific code is as follows:


/// <summary>
 ///  Exception handling 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public void context_Error(object sender, EventArgs e)
 {
  // Exceptions are handled here 
  HttpContext ctx = HttpContext.Current;
  HttpResponse response = ctx.Response;
  HttpRequest request = ctx.Request;

  // Get to HttpUnhandledException Exception, which contains the 1 Actual exceptions 
  Exception ex = ctx.Server.GetLastError();
  // Actual anomaly occurred 
  Exception iex = ex.InnerException;

  ////  Exception log landing 
  ////  Exception log landing includes: recording exception text file log, or recording exception log database, etc. (according to the actual project needs to make records) 

  ////  Get the request method 
  string httpMethod = request.HttpMethod;
  ////  If it is POST Request, it is one of the following requests 1
  //// ajax Interface request 
  //// form Form submission 
  ////  For exceptions in this situation, you do not need to jump to your own exception error page, but directly return to the corresponding system exception 
  if (httpMethod.ToUpper() == "POST")
  {
  ////  Build Returns Object Values 
  MRequestResult requestResultM = new MRequestResult();
  requestResultM.RequestResultCode = RequestResultCodeEnum.Fail;
  requestResultM.ResultValue = " System anomaly , Please contact the administrator! ";

  response.Write(JsonConvert.SerializeObject(requestResultM, Formatting.Indented));
  ctx.Server.ClearError();// Clean up exceptions in time after processing 
  }
 }

Code example:

ajax request method and its logical processing instance code:


$(function () {
 $.ajax({
  async: true,
  type: "post",
  url: "../ActionTestResult/ContentResultTest",
  data: "name=xu",
  success: function (resultValue) {

  if (resultValue) {
   ////  Analyze the processing result 
   var resultObj = $.parseJSON(resultValue);

   ////  When RequestResultCode==1  Indicates that the request was successful 
   //// (Remarks: It does not mean that the processing is successful. Whether the processing is successful or not needs to be passed ResultValue The value of is resolved according to the interface contract and processed logically) 
   if (resultObj["RequestResultCode"] == 1) {
   ////  Custom request success logic processing 
   ////  By parsing the specific ResultValue Do corresponding logical processing for the value of .....
   if (resultObj["ResultValue"]) {
    var doResult = resultObj["ResultValue"].split('^');
    if (doResult && doResult.length > 1) {
    if (doResult[0] == 1) {
     ////  Explain that the processing is successful, and do the corresponding logical processing 
     alert(" Handle successfully! ");
    } else {
     ////  Processing failure 
     alert(doResult[1]);
    }

    } else {
    alert(" Operation failed! ");
    }

   } else {
    alert(" Unknown result ");
   }

   } else {
   ////  Explain the request exception 
   ////  Custom logical processing 
   alert(resultObj["ResultValue"]);
   }
  } else {
   ////  Custom logical processing 
   alert(" Operation failed! ");
  }

  console.log(resultValue);
  },
  error: function (data) {
  ////  Custom logical processing 
  alert(" System exception, please contact the administrator. Telephone: 8888888");
  console.log(data);
  }
 });
 });

Background request acceptance instance code for ajax:


/// <summary>
 ///  Test 
 /// </summary>
 /// <returns></returns>
 public ContentResult ContentResultTest(string name)
 {
  ////  Build request processing results Model
  MRequestResult requestResultM = new MRequestResult() { RequestResultCode = RequestResultCodeEnum.Success };

  ////  Business processing results 
  string doResult = string.Empty;

  ////  This time, I made a simple parameter non-empty judgment, only 1 Examples 
  ////  The processing result in this example is only passed by ^ Links indicate that during actual processing, the results can be passed through 1 A Json String 
  if (string.IsNullOrEmpty(name))
  {
  doResult = "-1^ Operation failed: Name cannot be empty! ";
  }
  else
  {
  /////  Other custom business logic processing, omitted here .....
  doResult = "1^ Operation successful ";
  }

  requestResultM.ResultValue = doResult;
  ////  Return results 
  return Content(JsonConvert.SerializeObject(requestResultM, Formatting.Indented));
 }

Do you think it's a bit round? I have limited expression ability and don't understand comments and exchanges?
Finally: Personal ability is limited. Maybe the solution is not friendly. There is a better solution. Welcome to leave a message and exchange, give more advice and give more advice

Summarize


Related articles: