I have asp.net core application. The implementation of configure method redirects the user to \"Error\" page when there is an exception ( in non Development environment)
You can use to handle exceptions UseExceptionHandler()
, put this code in your
Startup.cs
.
UseExceptionHandler can be used to handle exceptions globally. You can get all the details of exception object like Stack Trace, Inner exception and others. And then you can show them on screen. Here
Here You can read more about this diagnostic middleware and find how using IExceptionFilter
and by creating your own custom exception handler.
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace}";
await context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
}
);
You have to also delete default setting like UseDeveloperExceptionPage()
, if you use it, it always show default error page.
if (env.IsDevelopment())
{
//This line should be deleted
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
You should write your own middleware to handle custom exception handling. And make sure you add it towards the beginning (first if possible) of your middleware stack because exceptions that happen in middleware that is "earlier" in a stack will not be handled.
Example:
public class CustomExceptionMiddleware
{
private readonly RequestDelegate _next;
public CustomExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception e)
{
// Handle exception
}
}
}