{"id":163,"date":"2022-08-26T14:11:33","date_gmt":"2022-08-26T06:11:33","guid":{"rendered":"https:\/\/miie.net\/?p=163"},"modified":"2022-08-26T14:11:33","modified_gmt":"2022-08-26T06:11:33","slug":"ultimate-asp-net-core-web-api-chapter5-global-error-handling","status":"publish","type":"post","link":"https:\/\/diji.net\/?p=163","title":{"rendered":"Chapter5:GLOBAL ERROR HANDLING"},"content":{"rendered":"<h1>5 GLOBAL ERROR HANDLING<\/h1>\n<p>Exception handling helps us deal with the unexpected behavior of our system. To handle exceptions, we use the <strong>try-catch<\/strong> block in our code as well as the <strong>finally<\/strong> keyword to clean up our resources afterwards.<br \/>\n\u5f02\u5e38\u5904\u7406\u6709\u52a9\u4e8e\u6211\u4eec\u5904\u7406\u7cfb\u7edf\u7684\u610f\u5916\u884c\u4e3a\u3002\u4e3a\u4e86\u5904\u7406\u5f02\u5e38\uff0c\u6211\u4eec\u5728\u4ee3\u7801\u4e2d\u4f7f\u7528 <strong>try-catch<\/strong> \u5757\u4ee5\u53ca <strong>finally<\/strong> \u5173\u952e\u5b57\u6765\u6e05\u7406\u8d44\u6e90\u3002<\/p>\n<p>Even though there is nothing wrong with the try-catch blocks in our Actions in the Web API project, we can extract all the exception handling logic into a single centralized place. By doing that, we make our actions cleaner, more readable, and the error handling process more maintainable.<br \/>\n\u5c3d\u7ba1 Web API \u9879\u76ee\u4e2d\u7684\u64cd\u4f5c\u4e2d\u7684 try-catch \u5757\u6ca1\u6709\u9519\uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u5c06\u6240\u6709\u5f02\u5e38\u5904\u7406\u903b\u8f91\u63d0\u53d6\u5230\u4e00\u4e2a\u96c6\u4e2d\u7684\u4f4d\u7f6e\u3002\u901a\u8fc7\u8fd9\u6837\u505a\uff0c\u6211\u4eec\u4f7f\u6211\u4eec\u7684\u64cd\u4f5c\u66f4\u5e72\u51c0\uff0c\u66f4\u5177\u53ef\u8bfb\u6027\uff0c\u5e76\u4e14\u9519\u8bef\u5904\u7406\u8fc7\u7a0b\u66f4\u6613\u4e8e\u7ef4\u62a4\u3002<\/p>\n<p>In this chapter, we are going to refactor our code to use the built-in middleware and our custom middleware for global error handling to demonstrate the benefits of this approach.<br \/>\n\u5728\u672c\u7ae0\u4e2d\uff0c\u6211\u4eec\u5c06\u91cd\u6784\u4ee3\u7801\uff0c\u4ee5\u4f7f\u7528\u5185\u7f6e\u4e2d\u95f4\u4ef6\u548c\u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef6\u8fdb\u884c\u5168\u5c40\u9519\u8bef\u5904\u7406\uff0c\u4ee5\u6f14\u793a\u6b64\u65b9\u6cd5\u7684\u4f18\u52bf\u3002<\/p>\n<h2>5.1 Handing Errors Globally with Built-In Middleware<\/h2>\n<p>The <strong>UseExceptionHandler<\/strong> middleware is a built-in middleware that we can use to handle exceptions. So, let\u2019s dive into the code to see this middleware in action.<br \/>\n<strong>UseExceptionHandler<\/strong> \u4e2d\u95f4\u4ef6\u662f\u4e00\u4e2a\u5185\u7f6e\u7684\u4e2d\u95f4\u4ef6\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u6765\u5904\u7406\u5f02\u5e38\u3002\u56e0\u6b64\uff0c\u8ba9\u6211\u4eec\u6df1\u5165\u7814\u7a76\u4ee3\u7801\uff0c\u770b\u770b\u8fd9\u4e2a\u4e2d\u95f4\u4ef6\u7684\u5b9e\u9645\u6548\u679c\u3002<\/p>\n<p>We are going to create a new <strong>ErrorModel<\/strong> folder in the Entities project, and add the new class ErrorDetails in that folder:<br \/>\n\u6211\u4eec\u5c06\u5728<strong>Entities<\/strong>\u9879\u76ee\u4e2d\u521b\u5efa\u4e00\u4e2a\u65b0\u7684 <strong>ErrorModel<\/strong> \u6587\u4ef6\u5939\u9879\u76ee\uff0c\u5e76\u5728\u8be5\u6587\u4ef6\u5939\u4e2d\u6dfb\u52a0\u65b0\u7c7b <strong>ErrorDetails<\/strong>\uff1a<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing System.Text.Json;\nnamespace Entities.ErrorModel\n{\n    public class ErrorDetails \n    { \n        public int StatusCode { get; set; } \n        public string Message { get; set; } \n        public override string ToString() =&gt; JsonSerializer.Serialize(this);\n    }\n}\n<\/pre>\n<p>We are going to use this class for the details of our error message.<br \/>\n\u6211\u4eec\u5c06\u4f7f\u7528\u6b64\u7c7b\u6765\u4e86\u89e3\u9519\u8bef\u6d88\u606f\u7684\u8be6\u7ec6\u4fe1\u606f\u3002<\/p>\n<p>To continue, in the Extensions folder in the main project, we are going to add a new static class: <strong>ExceptionMiddlewareExtensions.cs<\/strong>.<br \/>\n\u4e3a\u4e86\u7ee7\u7eed\uff0c\u5728\u4e3b\u9879\u76ee\u7684\u6269\u5c55\u6587\u4ef6\u5939\u4e2d\uff0c\u6211\u4eec\u5c06\u6dfb\u52a0\u4e00\u4e2a\u65b0\u7684\u9759\u6001\u7c7b\uff1a<strong>ExceptionMiddlewareExtensions.cs<\/strong>\u3002<\/p>\n<p>Now, we need to modify it:<br \/>\n\u73b0\u5728\uff0c\u6211\u4eec\u9700\u8981\u4fee\u6539\u5b83\uff1a<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Contracts;\nusing Entities.ErrorModel;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Diagnostics;\nusing Microsoft.AspNetCore.Http;\nusing System.Net;\n\nnamespace CompanyEmployees.Extensions\n{\n    public static class ExceptionMiddlewareExtensions {\n        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger) \n        { \n            app.UseExceptionHandler(appError =&gt; \n            { \n                appError.Run(async context =&gt; {\n                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; \n                    context.Response.ContentType = &quot;application\/json&quot;; \n                    var contextFeature = context.Features.Get&lt;IExceptionHandlerFeature&gt;(); \n                    if (contextFeature != null) \n                    { \n                        logger.LogError($&quot;Something went wrong: {contextFeature.Error}&quot;); \n                        await context.Response.WriteAsync(new ErrorDetails() \n                        { \n                              StatusCode = context.Response.StatusCode, \n                              Message = &quot;Internal Server Error.&quot; \n                              }.ToString()); \n                    } \n                }); \n            }); \n        } \n    }\n}\n<\/pre>\n<p>In the code above, we\u2019ve created an extension method in which we\u2019ve registered the <strong>UseExceptionHandler<\/strong> middleware. Then, we\u2019ve populated the status code and the content type of our response, logged the error message, and finally returned the response with the custom created object.<br \/>\n\u5728\u4e0a\u9762\u7684\u4ee3\u7801\u4e2d\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a\u6269\u5c55\u65b9\u6cd5\uff0c\u5728\u8be5\u65b9\u6cd5\u4e2d\u6ce8\u518c\u4e86 <strong>UseExceptionHandler<\/strong> \u4e2d\u95f4\u4ef6\u3002\u7136\u540e\uff0c\u6211\u4eec\u586b\u5145\u4e86\u54cd\u5e94\u7684\u72b6\u6001\u4ee3\u7801\u548c\u5185\u5bb9\u7c7b\u578b\uff0c\u8bb0\u5f55\u4e86\u9519\u8bef\u6d88\u606f\uff0c\u6700\u540e\u8fd4\u56de\u4e86\u5e26\u6709\u81ea\u5b9a\u4e49\u521b\u5efa\u5bf9\u8c61\u7684\u54cd\u5e94\u3002<\/p>\n<p>5.2 Starpup Class Modification<br \/>\nTo be able to use this extension method, let\u2019s modify the <strong>Configure<\/strong> method inside the <strong>Startup<\/strong> class:<br \/>\n\u4e3a\u4e86\u80fd\u591f\u4f7f\u7528\u6b64\u6269\u5c55\u65b9\u6cd5\uff0c\u8ba9\u6211\u4eec\u4fee\u6539<strong>Configure<\/strong> <strong>Startup<\/strong> \u7c7b\u4e2d\u7684\u65b9\u6cd5\uff1a<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)\n        {\n            if (env.IsDevelopment())\n            {\n                app.UseDeveloperExceptionPage();\n            }\n            else\n            {\n                app.UseHsts();\n            }\n\n            app.ConfigureExceptionHandler(logger);\n            app.UseHttpsRedirection();\n            app.UseStaticFiles();\n\n            app.UseCors(&quot;CorsPolicy&quot;);\n            app.UseForwardedHeaders(new ForwardedHeadersOptions\n            {\n                ForwardedHeaders = ForwardedHeaders.All\n            });\n\n            app.UseRouting();\n\n            app.UseAuthorization();\n\n            app.UseEndpoints(endpoints =&gt;\n            {\n                endpoints.MapControllers();\n            });\n        }\n<\/pre>\n<\/p>\n<p>Finally, let\u2019s remove the <strong>try-catch<\/strong> block from our code:<br \/>\n\u6700\u540e\uff0c\u8ba9\u6211\u4eec\u4ece\u4ee3\u7801\u4e2d\u5220\u9664 <strong>try-catch<\/strong> \u5757\uff1a<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing AutoMapper;\nusing Contracts;\nusing Entities.DataTransferObjects;\nusing Microsoft.AspNetCore.Mvc;\nusing System;\nusing System.Collections.Generic;\n\nnamespace CompanyEmployees.Controllers\n{\n    &#x5B;Route(&quot;api\/companies&quot;)]\n    &#x5B;ApiController]\n    public class CompaniesController : ControllerBase\n    {\n        private readonly IRepositoryManager _repository; \n        private readonly ILoggerManager _logger; \n        private readonly IMapper _mapper; \n        public CompaniesController(IRepositoryManager repository, ILoggerManager logger, IMapper mapper) \n        { \n            _repository = repository; \n            _logger = logger; \n            _mapper = mapper;\n        }\n\n        &#x5B;HttpGet]\n        public IActionResult GetCompanies()\n        {\n            \/\/try\n            \/\/{\n            \/\/    var companies = _repository.Company.GetAllCompanies(trackChanges: false);\n            \/\/    var companiesDto = _mapper.Map&lt;IEnumerable&lt;CompanyDto&gt;&gt;(companies);\n            \/\/    return Ok(companiesDto);\n            \/\/}\n            \/\/catch (Exception ex)\n            \/\/{\n            \/\/    _logger.LogError($&quot;Something went wrong in the {nameof(GetCompanies)} action {ex}&quot;);\n            \/\/    return StatusCode(500, &quot;Internal server error&quot;);\n            \/\/}\n\n            var companies = _repository.Company.GetAllCompanies(trackChanges: false); \n            var companiesDto = _mapper.Map&lt;IEnumerable&lt;CompanyDto&gt;&gt;(companies); \n            return Ok(companiesDto);\n        }\n    }\n}\n<\/pre>\n<p>And there we go. Our action method is much cleaner now. More importantly, we can reuse this functionality to write more readable actions in the future.<br \/>\n\u6211\u4eec\u5c31\u8fd9\u6837\u5427\u3002\u6211\u4eec\u7684\u884c\u52a8\u65b9\u6cd5\u73b0\u5728\u66f4\u5e72\u51c0\u4e86\u3002\u66f4\u91cd\u8981\u7684\u662f\uff0c\u6211\u4eec\u53ef\u4ee5\u91cd\u7528\u6b64\u529f\u80fd\uff0c\u4ee5\u4fbf\u5728\u5c06\u6765\u7f16\u5199\u66f4\u5177\u53ef\u8bfb\u6027\u7684\u64cd\u4f5c\u3002<\/p>\n<h2>5.3 Testing the Result<\/h2>\n<p>To inspect this functionality, let\u2019s add the following line to the <strong>GetCompanies<\/strong> action, just to simulate an error:<br \/>\n\u8981\u68c0\u67e5\u6b64\u529f\u80fd\uff0c\u8ba9\u6211\u4eec\u5c06\u4ee5\u4e0b\u884c\u6dfb\u52a0\u5230<strong>GetCompanies<\/strong> \u64cd\u4f5c\uff0c\u53ea\u662f\u4e3a\u4e86\u6a21\u62df\u9519\u8bef\uff1a<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nthrow new Exception(&quot;Exception&quot;);\n<\/pre>\n<p>And send a request from Postman:<br \/>\n\u5e76\u53d1\u9001\u90ae\u9012\u5458\u7684\u8bf7\u6c42\uff1a<br \/>\n<a href=\"https:\/\/localhost:5001\/api\/companies\"><a href=\"https:\/\/localhost:5001\/api\/companies\"><a href=\"https:\/\/localhost:5001\/api\/companies\">https:\/\/localhost:5001\/api\/companies<\/a><\/a><\/a><\/p>\n<p><img decoding=\"async\" src=\"\/img\/20220824-ultimate-asp-net-core-web-api\/Image_5001.jpg\" alt=\"alt\" \/><\/p>\n<p>We can check our log messages to make sure that logging is working as well.<br \/>\n\u6211\u4eec\u53ef\u4ee5\u68c0\u67e5\u65e5\u5fd7\u6d88\u606f\uff0c\u4ee5\u786e\u4fdd\u65e5\u5fd7\u8bb0\u5f55\u4e5f\u6b63\u5e38\u5de5\u4f5c\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>5 GLOBAL ERROR HANDLING Exception handling helps us deal with the unexpected behavior of our system. To handle exceptions, we use the try-catch block in our code as well as the finally keyword to clean up our resources afterwards. \u5f02\u5e38\u5904\u7406\u6709\u52a9\u4e8e\u6211\u4eec\u5904\u7406\u7cfb\u7edf\u7684\u610f\u5916\u884c\u4e3a\u3002\u4e3a\u4e86\u5904\u7406\u5f02\u5e38\uff0c\u6211\u4eec\u5728\u4ee3\u7801\u4e2d\u4f7f\u7528 try-catch \u5757\u4ee5\u53ca finally \u5173\u952e\u5b57\u6765\u6e05\u7406\u8d44\u6e90\u3002 Even though there is nothing wrong with the try-catch blocks in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[23],"class_list":["post-163","post","type-post","status-publish","format-standard","hentry","category-csharp","tag-ultimate-asp-net-core-web-api"],"_links":{"self":[{"href":"https:\/\/diji.net\/index.php?rest_route=\/wp\/v2\/posts\/163","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/diji.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/diji.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/diji.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/diji.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=163"}],"version-history":[{"count":0,"href":"https:\/\/diji.net\/index.php?rest_route=\/wp\/v2\/posts\/163\/revisions"}],"wp:attachment":[{"href":"https:\/\/diji.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/diji.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/diji.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}