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));

ASP.NET Core Posted Sep 20, 2020

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept