Custom error handling in ASP.NET MVC: Application_Error event in Global.asax
In ASP.NET MVC applications, the Application_Error event in Global.asax is crucial for handling unhandled exceptions and providing custom error pages.
Pass data to error controller
The current code in the Application_Error event determines the HTTP status code and sets the RouteData object to pass to the Error controller. However, the code does not provide a way to pass the exception details to the controller.
A robust approach is to use query string parameters to transmit exception information. The modified Application_Error code is as follows:
<code class="language-csharp">protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); Response.Clear(); HttpException httpException = exception as HttpException; if (httpException != null) { string action; switch (httpException.GetHttpCode()) { case 404: // 页面未找到 action = "HttpError404"; break; case 500: // 服务器错误 action = "HttpError500"; break; default: action = "General"; break; } // 清除服务器上的错误 Server.ClearError(); Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message)); } }</code>
Error Controller
The error controller will receive the exception message as a query string parameter:
<code class="language-csharp">// GET: /Error/HttpError404 public ActionResult HttpError404(string message) { return View("SomeView", message); }</code>
Notes
While this approach allows for flexible exception handling, please consider the following:
The above is the detailed content of How Can I Implement Custom Error Handling with Exception Details in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!