- The exception handling features help us deal with the unforeseen errors which could appear in our code.
- To handle exceptions we can use the try-catch block in our code as well as finally keyword to clean up resources afterward.
Developer Exception Page
- To configure an app to display a page that shows detailed information about exceptions, install the
Microsoft.AspNetCore.Diagnostics
package.
- Put
UseDeveloperExceptionPage
before any middleware you want to catch exceptions in, such as app.UseMvc
.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
}
Custom Exception Handling Page
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseExceptionHandler("/error");
}
- In an MVC app, don't explicitly decorate the error handler action method with HTTP method attributes, such as
HttpGet
.
- Using explicit verbs could prevent some requests from reaching the method.
[Route("/Error")]
public IActionResult Index()
{
// Handle error here
}
Configuring Status Code Pages
- By default, an app doesn't provide a rich status code page for HTTP status codes, such as 404 Not Found.
- To provide status code pages, configure the Status Code Pages Middleware by adding a line to the
Startup.Configure
method:
app.UseStatusCodePages();
- By default, Status Code Pages Middleware adds simple, text-only handlers for common status codes, such as 404.
- The middleware supports several extension methods. One method takes a lambda expression:
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
- Another method takes a content type and format string:
app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");