{"id":4180,"date":"2021-10-14T07:57:00","date_gmt":"2021-10-14T07:57:00","guid":{"rendered":"https:\/\/viewmyprojects.com\/winwirewp\/?p=4180"},"modified":"2023-11-29T10:07:01","modified_gmt":"2023-11-29T10:07:01","slug":"global-exception-handling-asp-net-core-web-apis","status":"publish","type":"post","link":"https:\/\/viewmyprojects.com\/winwirewp\/blog\/global-exception-handling-asp-net-core-web-apis\/","title":{"rendered":"Global Exception Handling \u2013 ASP.Net Core Web APIs"},"content":{"rendered":"\n<p>Exception handling is one of the most important part of any application that needs to be addressed and implemented properly. With ASP.NET Core, things have changed and are in better shape to implement exception handling. Implementing exception handling for every action method in API, is quite time-consuming and requires extra efforts. So, in this post, find out how to implement global exception handling in&nbsp;<a href=\"https:\/\/viewmyprojects.com\/winwirewp\/building-modern-web-apps-using-asp-net-5\/\" target=\"_blank\" rel=\"noreferrer noopener\">ASP.NET<\/a>&nbsp;Core Web API.<\/p>\n\n\n\n<p>The benefit of implementing global exception handling is that you need to implement in at one place. Any exception occurs in your application will be handled, even when you add new controllers or new methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Global Exception Handling in ASP.NET Core Web APIs<\/h3>\n\n\n\n<p>Exceptions are something inevitable in any application This can mostly occur due to external factors as well, like network issues and so on. If these exceptions are not handled within the application, it may even lead the entire application to terminations and data loss.<\/p>\n\n\n\n<p>Here are a couple of ways to implement an exception handling globally.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">First Method<\/h3>\n\n\n\n<p>Using IExceptionHandler and creating custom exception handler. The interface looks like,<\/p>\n\n\n\n<p>namespace GlobalException<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>public interface IExceptionHandler:IFilterMetadata<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>void OnException(ExceptionContext context);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>As you can see, there is only one method which needs to be implemented. This method gets called in case of any unhandled exception. So, let\u2019s create a class which implements IExceptionHandler.<\/p>\n\n\n\n<p>public class CustomExceptionHandler : IExceptionFilter<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>public void OnException(ExceptionContext context)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>HttpStatusCode status = HttpStatusCode.InternalServerError;<\/p>\n\n\n\n<p>String message = String.Empty;<\/p>\n\n\n\n<p>var exceptionType = context.Exception.GetType();<\/p>\n\n\n\n<p>if (exceptionType == typeof(UnauthorizedAccessException))<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>message = \u201cUnauthorized Access\u201d;<\/p>\n\n\n\n<p>status = HttpStatusCode.Unauthorized;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>else if (exceptionType == typeof(NotImplementedException))<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>message = \u201cA server error occurred.\u201d;<\/p>\n\n\n\n<p>status = HttpStatusCode.NotImplemented;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>else<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>message = context.Exception.Message;<\/p>\n\n\n\n<p>status = HttpStatusCode.NotFound;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>context.ExceptionHandled = true;<\/p>\n\n\n\n<p>HttpResponse response = context.HttpContext.Response;<\/p>\n\n\n\n<p>response.StatusCode = (int)status;<\/p>\n\n\n\n<p>response.ContentType = \u201capplication\/json\u201d;<\/p>\n\n\n\n<p>var err = message + \u201d \u201d + context.Exception.StackTrace;<\/p>\n\n\n\n<p>response.WriteAsync(err);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Here, the code checks for the exception type and set the message and status properties accordingly.<\/p>\n\n\n\n<p>Finally, add the filter in the ConfigureServices method of Startup class.<\/p>\n\n\n\n<p>public void ConfigureServices(IServiceCollection services)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>services.AddControllers();<\/p>\n\n\n\n<p>services.AddSwaggerGen(c =&gt;<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>c.SwaggerDoc(\u201cv1\u201d, new OpenApiInfo { Title = \u201cGlobalException\u201d, Version = \u201cv1\u201d });<\/p>\n\n\n\n<p>});<\/p>\n\n\n\n<p>services.AddMvc(<\/p>\n\n\n\n<p>config =&gt; {<\/p>\n\n\n\n<p>config.Filters.Add(typeof(CustomExceptionHandler));<\/p>\n\n\n\n<p>});<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Now when you run the application and exception occurs, then it will be handled on Exception method. In one of the controller actions divide a number by zero (0). A custom exception class can also be created to infuse custom error details.<\/p>\n\n\n\n<p>[HttpGet]<\/p>\n\n\n\n<p>public decimal Get()<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>var rng = 9;<\/p>\n\n\n\n<p>return rng\/0 ;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>The following exception will be displayed.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/11\/Picture2-1-1.webp\" alt=\"Global Exception Handling - ASP.Net Core Web APIs\" class=\"wp-image-4182\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Second Method<\/h3>\n\n\n\n<p>ASP.NET Core is shipped with some inbuilt middleware components. And one of the inbuilt ASP.NET Core diagnostic middleware is&nbsp;<a href=\"https:\/\/docs.microsoft.com\/en-us\/aspnet\/core\/web-api\/handle-errors?view=aspnetcore-5.0\" target=\"_blank\" rel=\"noreferrer noopener\">UseExceptionHandler.<\/a><\/p>\n\n\n\n<p>The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.<\/p>\n\n\n\n<p>app.UseExceptionHandler(<\/p>\n\n\n\n<p>options =&gt;<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>options.Run(<\/p>\n\n\n\n<p>async context =&gt;<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;<\/p>\n\n\n\n<p>context.Response.ContentType = \u201ctext\/html\u201d;<\/p>\n\n\n\n<p>var ex = context.Features.Get&lt;IExceptionHandlerFeature&gt;();<\/p>\n\n\n\n<p>if (ex != null)<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>var err = $\u201d&lt;h1&gt;Error: {ex.Error.Message}&lt;\/h1&gt;{ex.Error.StackTrace }\u201d;<\/p>\n\n\n\n<p>await context.Response.WriteAsync(err).ConfigureAwait(false);<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>});<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>);<\/p>\n\n\n\n<p>Put this inside configure() of startup.cs file. Let\u2019s throw some exception to test it. In one of the controller action divide a number by zero (0).<\/p>\n\n\n\n<p>[HttpGet]<\/p>\n\n\n\n<p>public decimal Get()<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>var rng = 9;<\/p>\n\n\n\n<p>return rng\/0 ;<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Run the application and you should see following. You can also debug and check in case of exception, it is hitting the app.UseExceptionHandler() code.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/11\/Picture2-1-1.webp\" alt=\"Global Exception Handling - ASP.Net Core Web APIs\" class=\"wp-image-4182\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Get started with Global Exception Handling<\/h3>\n\n\n\n<p>This post highlights two approaches to handling exceptions globally, either via inbuilt middleware or an exception filter. This approach will speed up the development process and help developers to focus on implementing the business logic. This approach also helps test the exception handling separately and ensures that every error in your Web API application is caught.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exception handling is one of the most important part of any application that needs to be addressed and implemented properly. With ASP.NET Core, things have changed and are in better shape to implement exception handling. Implementing exception handling for every action method in API, is quite time-consuming and requires extra efforts. So, in this post,&hellip; <a class=\"more-link\" href=\"https:\/\/viewmyprojects.com\/winwirewp\/blog\/global-exception-handling-asp-net-core-web-apis\/\">Continue reading <span class=\"screen-reader-text\">Global Exception Handling \u2013 ASP.Net Core Web APIs<\/span><\/a><\/p>\n","protected":false},"author":9,"featured_media":16373,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_eb_attr":"","_uag_custom_page_level_css":"","footnotes":""},"categories":[59,61],"tags":[],"class_list":["post-4180","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blogs","category-app-modernization-blogs","entry"],"acf":[],"featured_image_src":"https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp","author_info":{"display_name":"Sohan","author_link":"https:\/\/viewmyprojects.com\/winwirewp\/author\/sohan\/"},"views":4874,"uagb_featured_image_src":{"full":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp",800,440,false],"thumbnail":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs-150x150.webp",150,150,true],"medium":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs-300x165.webp",300,165,true],"medium_large":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs-768x422.webp",750,412,true],"large":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp",750,413,false],"1536x1536":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp",800,440,false],"2048x2048":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp",800,440,false],"post-thumbnail":["https:\/\/viewmyprojects.com\/winwirewp\/wp-content\/uploads\/2023\/10\/Global-Exception-Handling-\u2013-ASP.Net-Core-Web-APIs.webp",800,440,false]},"uagb_author_info":{"display_name":"Sohan","author_link":"https:\/\/viewmyprojects.com\/winwirewp\/author\/sohan\/"},"uagb_comment_info":0,"uagb_excerpt":"Exception handling is one of the most important part of any application that needs to be addressed and implemented properly. With ASP.NET Core, things have changed and are in better shape to implement exception handling. Implementing exception handling for every action method in API, is quite time-consuming and requires extra efforts. So, in this post,&hellip;&hellip;","_links":{"self":[{"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/posts\/4180","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/comments?post=4180"}],"version-history":[{"count":2,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/posts\/4180\/revisions"}],"predecessor-version":[{"id":17904,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/posts\/4180\/revisions\/17904"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/media\/16373"}],"wp:attachment":[{"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/media?parent=4180"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/categories?post=4180"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/viewmyprojects.com\/winwirewp\/wp-json\/wp\/v2\/tags?post=4180"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}