0% found this document useful (0 votes)
50 views5 pages

Global Error Handling Aspnetcore

Global Error Handling Aspnetcore

Uploaded by

Fabian Cabrera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
50 views5 pages

Global Error Handling Aspnetcore

Global Error Handling Aspnetcore

Uploaded by

Fabian Cabrera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 5
Global Error Handling in ASP.NET Core Web API Posted by Marinko Spasojovi | Jul 23, 2018 | 18 Poa Ly cy CODE MAZE The exception handling features help us deal wth the unforeseen errors which could appear in aur code. To handle exceptions we can use the ch blockin our code as well as £ins1iy Keyword to clean up resources afterward Even though there is nothing wrong with the try-catch blocks in our Actions in Web API project, we can extract all he exception handling logic into a single centralized place. By doing that, we make our actions more readable andthe error handling process more ‘maintainable, if we want to make our actions even more readable and maintainable, we can implement Action Fiters. We wont talk about action fiers inthis article but we strongly recommend reading our post Acton Filer in NET Core In this atc, we are going to handle rors by using @ xy and our custom middleware for global error handling to demonstrate the benofits ofthis approach block fst and then rewrite our code by using buil-n middleware To download the source code for our starting project, you can visit the Global error handling start project For the finished projec afer to Global eror hanalng end project Inhis arte, we are going ota abou + ror Handling wih Ty-Cateh Block + Handing Errors Gobel ith the Buln Midleware + Handing Errors Globally with the Custom Mideleware + Conclusion Error Handling with Try-Catch Block To star off wth this example, lets open the Values Controller from the starting project (Global-Erro-Handling-Star projec) In this project, we can finda single Get (} method and an injected zogger servic. Its common practice to include the log messages while handling errors, therefore we have created the Loggestanager service It logs all the messages tothe © drive, but you can change thal by modifying the path in the ntog.contig fle, For more information about how to use Nlog in NET Core, you can vist Logging with NLos, Now, ls macify our action method to return a result and log some messages: T [using Systems 2 |using Loggerservice 3 [using Microsoft .asphetCore. we; namespace Globaltrrortlandling. Controllers 7 (Route(“api/{controller} 8) [Apicontrotier] 9 public class ValuesControlier : Contrellersase u private TLoggertanages _loze: a public ValuesController (ILoggerManager loz¢er) 14 16 1 Latepet] 13 public TActionfesult Get() 2» a wy 2 ote: 2s var students 2 logger. Loginfo(s"Returning {students.count) students| 29 return Ok(stucents) 30 > 2 eaten (Exception &x) 2 3 _logger-Logtrron(s"Sonething went wrong: (€x)" 26 Feturn StatusCode(s80, “Internal server error"); 36 3a) rer = Log Loginfo(*Fetching all the Students fron the pataManager.Getalistudents(); //simula} "When we send a request at his endpoint, we wil get tis result GET Y pinecone s5761Vepialuer ody ee ee Prewy oo | bY » Sb asf vnaner: ome, » : B > ‘And the log messages: NoEndeonmen ! We see that everyting is working as expected Now let's modify our code, right below the Getaiiscudenss{) method call, to force an exception: T throw new Exception’ “Exception while fetching all the students fron th Now, we send a equest thont$S76i/ephaloes ee And the log messages: ‘So this works just fine. Bu the downside of ths approach is that we need to repeat our cry-catch blocks in allthe actions in which we want to catch unhandled exceptions. Wel, there isa beter approach todo that Handling Errors Globally with the Built-In Middleware ‘The UsoexceptionHandier middleware is abu rn middleware that we can use o handle exceptions. So, let's dive inte the code to '82¢ this midaleware in action, Fist, we are going to add anew class exzcrDetaile inthe sodels folder: T [using NentonsoFt Jeon 3 -nanespace GlobslérrorHendling. Models 5 public class Errorbetails 7 public int Statuscode ( get; set 8 public string Message ( get set 1 n public override string Testring 2 B return JsonConver.SeriaLizeooject(this: ue 15 16 We are going to use this clas for the details of our error message. To contin lot's create anew folder extensions and anew staic class =xceptionMidd:evaresxtensions.os Inside it Now, we need to modty i using cl using Loy using Using MicrosoFe Asp D Using Wicrosofe.a using sys 8 [nanespace Giob21¢rrortiane! ing. Extensions 9 18, public static class Exceptiontidélewaretxtensions af 2 public static vold Configuretxceptionsandler(this TApplicatiol 1 po UseExcept ionHandlen (apperror 16 sppérror .Run(asyne cor uw xt. Response, StatusCode ~ (Int)HttaStatusCod ie Respon: inv Type = "application/json" 20 2 var cont 2 4 (conte 2 26 logger-Logerron(s"Sonething went wrong: (cont 2s 2% await R Weiteasync (new Errorde 27 8 stat = context Response. statusc 2 jessage ~ “Internal Server Error 30 Tostring 2 3 35 36) t text. Features .GetczExcep eure = null In the code above, we've created an extension method in which we've registered the Usesxceptioniandler middleware. Then, we've populated the status code and the content ype of our response, logged the eror message, and finally returned the response with the custom created object. ‘To be able to use this extension method, les modify the Configure method inside the startup class T [public vold Configure(tapplicationBullder app, EHostingénvironment 3 4F (env. Tsbevelopment 5 app. Usebeveloper=xceptionPage() 6 7 alse 8 ° 11 The default HSTS value is 30 days. You may want to change 1 app Uselsts 2 13 pp.Confiigureexceptiontandler ry 15, opp. UseitttpsRedirection’ 46 spp. Usetve v Final let's remove the try-catich block from our code: @ T [public Tactiontesuit Get 2 3 _Aogger-Logingo(*Fetching al the students fron the storage” 4 5| var students = patatanager.Getalistudents(); //simulation for th 6 7 throw new Exception(“Exception while fetching all the students 4 a 9 | _Logger.Logenfo(s"Returning {students.count} students.) 12, return Ok( students); ‘And there you go. Our action method is much cleaner now and what's more important we can reuse this functionality to write more readable actions in the future. So let's inspect the result: a ‘And the og messages: S Inseaa-necnoa(cicauee , cbjece > cosecell ) ees Excelent, Now, we are going to use a custom middleware for global ertor harding Handling Errors Globally with the Custom Middleware Lets erate a new folder named Custonexceptionsiiddleware and a class SxceptionMicdlewars.ce inside it Wo are going to modify that class: @ T [public class Exceptlonilddleware 3 private readonly RequestDelegate _new 4) private readonly TLoggertanages _lozs: 5 6 public Exceptiontiddleware Requestoelegate next, TLoggertanages 7 ¢ 8 longer = logger: 9 Thext = next 1 12) public asyne Task Tavokeasync(HttpContext»ttpcontext) rs try 16 await _next( Pry catch (Exception ex) 1s 2 “togser Logerror(s"Sonething went wrong: {ex)") 2 ‘anait HandletxceptionAsyne(¢epcontext, ex) 2 25, private static Task HandleExceptiontsync(HttpContext context, Exe wf 2 ype = "application/ json’ 2 (Ant)Httpstatuscode. Internalse

You might also like