Configure and Return Unhandled Errors using Custom Exception Middleware in Asp.Net Core 3.1 Web API

Implement Custom Exception Middleware in Asp.Net Core 3.1 Web API Application

November 24, 2020

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 { getset; }
    public string ErrorMessage { getset; }
 
    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(httpContextex);
        }
    }
 
    private Task ErrorAsync(HttpContext contextException 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 appIWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
 
    app.UseMiddleware<ExceptionMiddleware>();
 
    app.UseHttpsRedirection();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...