I am trying to use middleware for exception handling in my ASP.Net Core 5.0 project but it doesn't handle the exception and debugging stops the application when exception is thrown.
public class CustomExceptionMiddleWare
{
private readonly RequestDelegate _next;
public CustomExceptionMiddleWare(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var watch = Stopwatch.StartNew();
try
{
string message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path;
Console.WriteLine(message);
await _next(context);
watch.Stop();
message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path + " responded " +
context.Response.StatusCode.ToString() + " in " + watch.Elapsed.TotalMilliseconds + " ms";
Console.WriteLine(message);
}
catch (Exception ex)
{
watch.Stop();
await HandleException(context, ex, watch);
}
}
private Task HandleException(HttpContext context, Exception ex, Stopwatch watch)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
string message = "[Error] HTTP" + context.Request.Method + " - " + context.Response.StatusCode +
" Error Message " + ex.Message + " in " + watch.Elapsed.TotalMilliseconds + " ms";
Console.WriteLine(message);
var result = JsonConvert.SerializeObject(new { Error = ex.Message }, Formatting.None);
return context.Response.WriteAsync(result);
}
}
public static class CustomExceptionMiddlewareExtension
{
public static IApplicationBuilder UseCustomExceptionMiddleWare(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionMiddleWare>();
}
}
}
startup.cs :
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseCustomExceptionMiddleWare();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PatikaWebApi v1"));
}
//app.UseMiddleware<CustomExceptionMiddleWare>();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCustomExceptionMiddleWare();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
controller
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
BookDetailViewModel result;
GetBooksDetailQuery query = new GetBooksDetailQuery(_context,_mapper);
query.BookId = id;
GetBooksDetailQueryValidator validator = new GetBooksDetailQueryValidator();
validator.ValidateAndThrow(query);
result = query.Handle();
return Ok(result);
}
When the exception is thrown middleware doesn't handle the exception with Debug mode. I searched for the solution and i found one that removing app.UseDeveloperExceptionPage(); row didn't work for me.I have tried to change pipeline but didn't work either. What would be the solution ? Thank you for your attention.
Error is Exception User-Unhandled