Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
50 views
5 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
Download
Save
Save Global Error Handling Aspnetcore For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
50 views
5 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
Carousel Previous
Carousel Next
Download
Save
Save Global Error Handling Aspnetcore For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Global Error Handling Aspnetcore For Later
You are on page 1
/ 5
Search
Fullscreen
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 sys8 [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
C# .Net Exceptions
PDF
No ratings yet
C# .Net Exceptions
4 pages
Responsive Web Design With Oracle JET
PDF
100% (1)
Responsive Web Design With Oracle JET
16 pages
Exception Handlingc#
PDF
No ratings yet
Exception Handlingc#
17 pages
100 Nintendo Games To Play Before You Die - 5th Edition 2023
PDF
No ratings yet
100 Nintendo Games To Play Before You Die - 5th Edition 2023
164 pages
Exception Handling: Visual Programming Languages
PDF
No ratings yet
Exception Handling: Visual Programming Languages
47 pages
Improving On The Applications Behavior Slides
PDF
No ratings yet
Improving On The Applications Behavior Slides
27 pages
Using The WebLogic Scripting Tool PDF
PDF
No ratings yet
Using The WebLogic Scripting Tool PDF
25 pages
Exception Handling
PDF
No ratings yet
Exception Handling
40 pages
AWP Unit 3
PDF
No ratings yet
AWP Unit 3
21 pages
Methods Explained) : Public Actionresult Someerror (Try Catch (Exception Ex) (Return View ("Error") ) )
PDF
No ratings yet
Methods Explained) : Public Actionresult Someerror (Try Catch (Exception Ex) (Return View ("Error") ) )
33 pages
Chapter 3 Exeption
PDF
No ratings yet
Chapter 3 Exeption
30 pages
Unit 3 - DOT - NET - CORE
PDF
No ratings yet
Unit 3 - DOT - NET - CORE
56 pages
AWP Unit 3 and 4
PDF
No ratings yet
AWP Unit 3 and 4
18 pages
Chapter 3 - Exception Handling
PDF
No ratings yet
Chapter 3 - Exception Handling
13 pages
Chapter Four Slide C# STD
PDF
No ratings yet
Chapter Four Slide C# STD
30 pages
Errors Spring Boot
PDF
No ratings yet
Errors Spring Boot
24 pages
ch-3 Exception
PDF
No ratings yet
ch-3 Exception
31 pages
AWP Unit 3,4 and 5
PDF
No ratings yet
AWP Unit 3,4 and 5
26 pages
Awp Unit 3 - 23458533 - 2023 - 11 - 22 - 12 - 22
PDF
No ratings yet
Awp Unit 3 - 23458533 - 2023 - 11 - 22 - 12 - 22
43 pages
Ch-3 Edited Exception
PDF
No ratings yet
Ch-3 Edited Exception
29 pages
Exception Handling in C#: Understanding The Importance of Error Handling
PDF
No ratings yet
Exception Handling in C#: Understanding The Importance of Error Handling
21 pages
Handling Special Scenarios - Parallel Programming With C# and .NET - Fundamentals of Concurrency and Asynchrony Behind Fast-Paced Applications
PDF
No ratings yet
Handling Special Scenarios - Parallel Programming With C# and .NET - Fundamentals of Concurrency and Asynchrony Behind Fast-Paced Applications
39 pages
Chapter 3 - Exception Handling
PDF
No ratings yet
Chapter 3 - Exception Handling
13 pages
Exceptions and Object Lifetime
PDF
No ratings yet
Exceptions and Object Lifetime
27 pages
Name:-Vrushabh Shashikant Rasal Class:Tybsc-It ROLL NO:556 Div: A Subject:-Advanced Web Programming
PDF
No ratings yet
Name:-Vrushabh Shashikant Rasal Class:Tybsc-It ROLL NO:556 Div: A Subject:-Advanced Web Programming
9 pages
Session 5
PDF
No ratings yet
Session 5
23 pages
Chapter 4 WP With C# Exception Handling Student 1.0
PDF
No ratings yet
Chapter 4 WP With C# Exception Handling Student 1.0
29 pages
Exception Handling: Catching and Handling Exceptions
PDF
No ratings yet
Exception Handling: Catching and Handling Exceptions
14 pages
Exception Handling
PDF
No ratings yet
Exception Handling
8 pages
Exception Handling OOP PRESENTATION
PDF
No ratings yet
Exception Handling OOP PRESENTATION
22 pages
C# Assignment PDF
PDF
No ratings yet
C# Assignment PDF
49 pages
Exception Handling
PDF
No ratings yet
Exception Handling
17 pages
Errors, Bugs and Exceptions: Bugs: These Are, Simply Put, Errors On The Part of The Programmer. For
PDF
No ratings yet
Errors, Bugs and Exceptions: Bugs: These Are, Simply Put, Errors On The Part of The Programmer. For
16 pages
C# Assignemnt
PDF
No ratings yet
C# Assignemnt
13 pages
Unit 3: Exception Handling
PDF
No ratings yet
Unit 3: Exception Handling
12 pages
OCI C Unit 4
PDF
No ratings yet
OCI C Unit 4
18 pages
Exception Handling
PDF
No ratings yet
Exception Handling
7 pages
C#.net Exceptions
PDF
No ratings yet
C#.net Exceptions
27 pages
Exception Handling V1.0
PDF
No ratings yet
Exception Handling V1.0
24 pages
C Sharp - Exception Handling
PDF
No ratings yet
C Sharp - Exception Handling
6 pages
Chapter 1 (Error Handling and Tracing) PDF
PDF
No ratings yet
Chapter 1 (Error Handling and Tracing) PDF
15 pages
C# Programming Mandefro B
PDF
No ratings yet
C# Programming Mandefro B
6 pages
Unit Iv
PDF
No ratings yet
Unit Iv
17 pages
Error Handling: Using Httpresponse Exception
PDF
No ratings yet
Error Handling: Using Httpresponse Exception
10 pages
3 - Structured Exception Handling
PDF
No ratings yet
3 - Structured Exception Handling
11 pages
Exception Report
PDF
No ratings yet
Exception Report
14 pages
Exception Handling: Ankit Verma
PDF
No ratings yet
Exception Handling: Ankit Verma
8 pages
Exception and Exception Handling
PDF
No ratings yet
Exception and Exception Handling
11 pages
Error Handling in Large NET Projects - Best Practices
PDF
No ratings yet
Error Handling in Large NET Projects - Best Practices
10 pages
Exception Handlings in C#-DJ
PDF
No ratings yet
Exception Handlings in C#-DJ
3 pages
How To Check Memory Usage Per Process On LINUX
PDF
No ratings yet
How To Check Memory Usage Per Process On LINUX
6 pages
Unit 4
PDF
No ratings yet
Unit 4
8 pages
Execption Filters
PDF
No ratings yet
Execption Filters
8 pages
Adv Oop Lect15
PDF
No ratings yet
Adv Oop Lect15
6 pages
Error Handling 101
PDF
No ratings yet
Error Handling 101
6 pages
10 Handout 1
PDF
No ratings yet
10 Handout 1
3 pages
22aefexception Handling Techniques in ASP
PDF
No ratings yet
22aefexception Handling Techniques in ASP
3 pages
Step 1: Start by Creating An Error Folder Where All Errors
PDF
No ratings yet
Step 1: Start by Creating An Error Folder Where All Errors
3 pages
Logging & Error Handling
PDF
No ratings yet
Logging & Error Handling
2 pages
03 APR 2024 Exceptions
PDF
No ratings yet
03 APR 2024 Exceptions
2 pages
Validador de Excepciones Peor Aun Se Detiene Los Procesos
PDF
No ratings yet
Validador de Excepciones Peor Aun Se Detiene Los Procesos
1 page
Public
PDF
No ratings yet
Public
2 pages