How do you handle errors Globally in ASP.NET Core?

We can make use of the built-in UseExceptionHandler() middleware for catching Global Errors in ASP.NET Core.

app.UseExceptionHandler(err =>
   {
        err.Run(async ctx =>
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "application/json";
            // gets error detail
            var ex =  context.Features.Get<IExceptionHandlerPathFeature>();
            var error = new MyResponseModel() { Content = ex.Error.Message };
            await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
        });
    });

We can make use of the built-in UseExceptionHandler() middleware for catching Global Errors in ASP.NET Core.

app.UseExceptionHandler(err =>
   {
        err.Run(async ctx =>
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "application/json";
            // gets error detail
            var ex =  context.Features.Get<IExceptionHandlerPathFeature>();
            var error = new MyResponseModel() { Content = ex.Error.Message };
            await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
        });
    });

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *