In this article we will cover how to configure and return unhandled errors using Custom Exception Middleware in Asp.Net Core 3.1 Web API Application
ExceptionDetails.cs
Create ExceptionDetails Class with given properties. (This class will be returned in JSON format)
public class ExceptionDetails { public int ErrorCode { get; set; } public string ErrorMessage { get; set; } public override string ToString() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } }
ExceptionMiddleware.cs
Create ExceptionMiddleware Class as mentioned below. (This class will handle all the errors occurred during run time.)
public class ExceptionMiddleware { private readonly RequestDelegate _next; public ExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { await ErrorAsync(httpContext, ex); } } private Task ErrorAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return context.Response.WriteAsync(new ExceptionDetails() { ErrorCode = context.Response.StatusCode, ErrorMessage = $"Internal Server Error from the custom middleware.({ex.Message})" }.ToString()); } }
Startup.cs
Add ExceptionMiddleware inside the Configure method as mentioned below
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseMiddleware<ExceptionMiddleware>(); app.UseHttpsRedirection(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
Post Comments(0)