{"id":103965,"date":"2024-01-14T23:56:40","date_gmt":"2024-01-14T22:56:40","guid":{"rendered":"https:\/\/code-maze.com\/?p=103965"},"modified":"2024-01-14T23:56:40","modified_gmt":"2024-01-14T22:56:40","slug":"dotnet-use-iexceptionhandler-to-handle-exceptions","status":"publish","type":"post","link":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/","title":{"rendered":"How to Use IExceptionHandler to Handle Exceptions in .NET"},"content":{"rendered":"<p>Effective error handling plays a crucial role in shaping the behavior of our applications. It involves establishing consistent response formats for our applications, ensuring a standardized approach even when errors occur. .NET 8 comes with the IExceptionHandler abstraction which offers us a new improved approach to handling errors in our applications.<\/p>\n<p>In this article, we&#8217;re going to learn how we can use IExceptionHandler to handle exceptions in .NET.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/exception-handling\/IExceptionHandlerInterface\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s start.<\/p>\n<h2>What Is IExceptionHandler in .NET<\/h2>\n<p><code>IExceptionHandler<\/code> is an interface for handling exceptions in ASP.NET Core applications. It defines an interface that we can implement to handle different exceptions. This allows us to write custom logic for handling individual exceptions or groups of exceptions based on their type, in turn providing tailored responses, error messages as well as logging.<\/p>\n<h2>Why Use IExceptionHandler<\/h2>\n<p><code>IExceptionHandler<\/code> offers a powerful and flexible approach to handling exceptions in .NET APIs, empowering us to build more robust and user-friendly APIs. Also,<strong> we can implement <code>IExceptionHandler<\/code> in normal C# classes to handle different types of exceptions<\/strong>. This way, we make our applications modular and easy to maintain.<\/p>\n<p><code>IExceptionHandler<\/code> <strong>helps us tailor the responses to the specific exceptions, providing more informative error messages<\/strong>. This helps when building user interfaces such that we can redirect users to a dedicated error page whenever exceptions are thrown by our APIs.<\/p>\n<p>In addition to that, when using the <code>IExceptionHandler<\/code> interface, we don&#8217;t necessarily need to create custom global exception handlers for our applications because .NET 8 already has the middleware implemented for us through the <code>IExceptioHandler<\/code>.<\/p>\n<div style=\"padding: 20px; border-left: 5px gray solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To learn more about global exception handlers, be sure to check out our article <a href=\"https:\/\/code-maze.com\/global-error-handling-aspnetcore\/\" target=\"_blank\" rel=\"noopener\">Global Error Handling in ASP.NET Core Web API<\/a>.<\/div>\n<p>Let&#8217;s see how we can use <code>IExceptionHandler<\/code> in our applications.<\/p>\n<h2>Project Setup<\/h2>\n<p>Since <code>IExceptionHandler<\/code> ships with .NET 8, we can use it out of the box. First, let&#8217;s create a Web API project using the dotnet CLI command:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">dotnet new web<\/code><\/p>\n<p>For tests, we&#8217;ll simulate a library service. So let&#8217;s create a <code>Book<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Book\r\n{\r\n    public int Id { get; set; }\r\n    public string Title { get; set; }\r\n    public string Author { get; set; }\r\n}<\/pre>\n<p>Let&#8217;s also create an <code>ILibraryService<\/code> interface with two methods:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public interface ILibraryService\r\n{\r\n    Book GetById(int id);\r\n    List&lt;Book&gt; GetAllBooks();\r\n}<\/pre>\n<p>Next, let&#8217;s add an endpoint to test our implementation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">app.MapGet(\"\/books\", async context =&gt;\r\n{\r\n    var libraryService = context\r\n    .RequestServices\r\n    .GetRequiredService&lt;ILibraryService&gt;();\r\n\r\n    var allBooks = libraryService.GetAllBooks();\r\n    await context.Response.WriteAsJsonAsync(allBooks);\r\n});<\/pre>\n<p>Now, we can run our application and test the <code>\/books<\/code> endpoint to get a list of the books:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">[\r\n  {\r\n    \"id\": 1,\r\n    \"title\": \"The Catcher in the Rye\",\r\n    \"author\": \"J.D. Salinger\"\r\n  },\r\n  {\r\n    \"id\": 2,\r\n    \"title\": \"To Kill a Mockingbird\",\r\n    \"author\": \"Harper Lee\"\r\n  },\r\n  {\r\n    \"id\": 3,\r\n    \"title\": \"1984\",\r\n    \"author\": \"George Orwell\"\r\n  }\r\n]<\/pre>\n<p>This implies that our setup works as expected, let&#8217;s dig deeper into exception handling.<\/p>\n<h2>Using the IExceptionHandler Middleware in our Applications<\/h2>\n<p>Having set up our project, let&#8217;s now add the <code>GlobalExceptionHandler<\/code> class which implements <code>IExceptionHandler<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class GlobalExceptionHandler: IExceptionHandler\r\n{\r\n}<\/pre>\n<p>Then, let&#8217;s register our exception handler in the dependency injection container:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;();\r\nbuilder.Services.AddProblemDetails();<\/pre>\n<p>Whenever there&#8217;s an exception in our application, the <code>GlobalExceptionHandler<\/code> handler will be automatically invoked. The API will also generate <code>ProblemDetails<\/code> standardized responses as per <a href=\"https:\/\/datatracker.ietf.org\/doc\/html\/rfc7807\" target=\"_blank\" rel=\"nofollow noopener\">RFC 7807 specification<\/a>. This way, we have more control over how we intercept, handle, and format error responses.<\/p>\n<p>Finally, let&#8217;s add the middleware to the application request pipeline:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">app.UseExceptionHandler();<\/code><\/p>\n<p>Now, let&#8217;s proceed to handle exceptions.<\/p>\n<h3>The TryHandleAsync Method<\/h3>\n<p>The <code>IExceptionHandler<\/code> interface only has the <code>TryHandleAsync()<\/code> method that enables us to implement custom exception handling logic for different exceptions. The method t<span class=\"c\">ries to handle the specified exception asynchronously within the ASP.NET Core pipeline. It returns a task that represents <\/span><span class=\"c\">the asynchronous read operation. The <code>Result<\/code> property of the task contains the result of the exception-handling operation. If the exception is handled successfully, the method returns <code>true<\/code>, otherwise it returns <code>false<\/code>.<\/span><\/p>\n<p>Let&#8217;s add a custom implementation of <code>TryHandleAsync()<\/code> method in our middleware:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public async ValueTask&lt;bool&gt; TryHandleAsync(\r\n    HttpContext httpContext,\r\n    Exception exception,\r\n    CancellationToken cancellationToken)\r\n{\r\n    logger.LogError(\r\n        $\"An error occurred while processing your request: {exception.Message}\");\r\n\r\n    var problemDetails = new ProblemDetails\r\n    {\r\n        Status = (int)HttpStatusCode.InternalServerError,\r\n        Type = exception.GetType().Name,\r\n        Title = \"An unhandled error occurred\",\r\n        Detail = exception.Message\r\n    };\r\n\r\n    await httpContext\r\n        .Response\r\n        .WriteAsJsonAsync(problemDetails, cancellationToken);\r\n\r\n    return true;\r\n}<\/pre>\n<p>First, we log the exception, then use the <code>ProblemDetails<\/code> object to populate additional details of the exception. Please note that we have the flexibility to create a custom class for shaping the response, eliminating the need to rely exclusively on <code>ProblemDetails<\/code>.<\/p>\n<p>Let&#8217;s add an endpoint in the <code>Program<\/code> class\u00a0to test this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">app.MapGet(\"\/books\/get-by-author\", () =&gt;\r\n{\r\n    throw new NotImplementedException();\r\n});<\/pre>\n<p>Calling the endpoint, the application throws a <code>NotImplementedException<\/code> exception.\u00a0<\/p>\n<p>Let&#8217;s test this out:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"type\": \"NotImplementedException\",\r\n  \"title\": \"An unhandled error occurred\",\r\n  \"status\": 500,\r\n  \"detail\": \"The method or operation is not implemented.\"\r\n}<\/pre>\n<p>Our exception handler catches the exception, handles it, and returns the expected response format.<\/p>\n<p>Having learned how to set up and handle exceptions using <code>IExceptionHandler<\/code>, let&#8217;s see how we can handle different types of exceptions in our applications.<\/p>\n<h3>Handling Different Exception Types<\/h3>\n<p>When handling different types of errors, we implement different instances of <code>IExceptionHandler<\/code>, each handling a specific type of exception. Then, we can proceed to register each handler in the dependency injection container by calling the\u00a0 <code>AddExceptionHandler&lt;THandler&gt;()<\/code> extension method. It&#8217;s worth noting that when registering multiple exception handlers, we should follow the order we&#8217;d like to execute them.\u00a0<\/p>\n<p>Let&#8217;s create an exception handler to handle <code>BadHttpRequestException<\/code> exceptions:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public async ValueTask&lt;bool&gt; TryHandleAsync(\r\n    HttpContext httpContext,\r\n    Exception exception,\r\n    CancellationToken cancellationToken)\r\n{\r\n    logger.LogError($\"Bad request exception: {exception.Message}\");\r\n\r\n    if (exception is not BadHttpRequestException badRequestException)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    var errorResponse = new ErrorResponse\r\n    {\r\n        StatusCode = (int)HttpStatusCode.BadRequest,\r\n        Title = \"Bad Request\",\r\n        Message = badRequestException.Message\r\n    };\r\n\r\n    httpContext.Response.StatusCode = errorResponse.StatusCode;\r\n\r\n    await httpContext.Response.WriteAsJsonAsync(errorResponse, cancellationToken);\r\n\r\n    return true;\r\n}<\/pre>\n<p>Here, the <code>TryHandleAsync()<\/code> method uses the <code>errorResponse<\/code> object to return the exception details from the API, unlike the first exception handler which we used <code>ProblemDetails<\/code>. Having implemented the handler, let&#8217;s register it as a service:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddExceptionHandler&lt;BadRequestExceptionHandler&gt;();\r\nbuilder.Services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;();<\/pre>\n<p>This way, whenever we get a <code>BadHttpRequestException<\/code>, our new middleware <code>BadRequestExceptionHandler<\/code> will handle it. Any other exceptions will be handled by <code>GlobalExceptionHandler<\/code>.<\/p>\n<p>Let&#8217;s add an endpoint to test this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">app.MapGet(\"\/books\/{id}\", async context =&gt;\r\n{\r\n    var id = int.Parse(context.Request.RouteValues[\"id\"].ToString());\r\n    var libraryService = context.RequestServices.GetRequiredService&lt;ILibraryService&gt;();\r\n    var book = libraryService.GetById(id);\r\n\r\n    if (book is null)\r\n    {\r\n        throw new BadHttpRequestException($\"Book with Id {id} not found.\", StatusCodes.Status400BadRequest);\r\n    }\r\n\r\n    await context.Response.WriteAsJsonAsync(book);\r\n});<\/pre>\n<p>This endpoint gets a book by its <code>id<\/code> passed as a route parameter. If the book exists, we get a 200 success response with the data, otherwise, we get a <code>BadHttpRequestException<\/code>.<\/p>\n<p>Now, calling the endpoint with an <code>id<\/code> value that exists:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">GET https:\/\/localhost:7036\/books\/1<\/code><\/p>\n<p>We get a response with the book details:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"id\": 1,\r\n  \"title\": \"The Catcher in the Rye\",\r\n  \"author\": \"J.D. Salinger\"\r\n}<\/pre>\n<p>If we are to test with an <code>id<\/code> that doesn&#8217;t exist:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"shell\">GET https:\/\/localhost:7036\/books\/0<\/code><\/p>\n<p>We get a response with a 400 BadRequest status code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"title\": \"BadHttpRequestException\",\r\n  \"statusCode\": 400,\r\n  \"message\": \"Book with Id 0 not found.\"\r\n}<\/pre>\n<p>We could chain more exception handlers to handle the different exceptions by using the same approach.<\/p>\n<p>This far, there&#8217;s one potential problem. We could end up with a lot of classes in our applications all handling different exceptions. How about we improve this?<\/p>\n<p>Let&#8217;s modify our <code>GlobalExceptionHandler<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"14-25\">public async ValueTask&lt;bool&gt; TryHandleAsync(\r\n    HttpContext httpContext,\r\n    Exception exception,\r\n    CancellationToken cancellationToken)\r\n{\r\n    _logger.LogError(\r\n        $\"An error occurred while processing your request: {exception.Message}\");\r\n\r\n    var errorResponse = new ErrorResponse\r\n    {\r\n        Message = exception.Message\r\n    };\r\n\r\n    switch (exception)\r\n    {\r\n        case BadHttpRequestException:\r\n            errorResponse.StatusCode = (int)HttpStatusCode.BadRequest;\r\n            errorResponse.Title = exception.GetType().Name;\r\n            break;\r\n\r\n        default:\r\n            errorResponse.StatusCode = (int)HttpStatusCode.InternalServerError;\r\n            errorResponse.Title = \"Internal Server Error\";\r\n            break;\r\n    }\r\n\r\n    httpContext.Response.StatusCode = errorResponse.StatusCode;\r\n\r\n    await httpContext\r\n        .Response\r\n        .WriteAsJsonAsync(errorResponse, cancellationToken);\r\n\r\n    return true;\r\n}<\/pre>\n<p>Here, we add a switch statement which we can extend to handle other exception types. In case there&#8217;s no matching exception, the application throws the default <code>InternalServerError<\/code> exception. This way, we only register one exception handler in the dependency injection container instead of registering multiple handlers.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we&#8217;ve learned how to handle exceptions using the IExceptionHandler interface introduced in .NET 8. We&#8217;ve learned how we can set it up in our applications and handle different types of exceptions thrown by our applications. We&#8217;ve also learned why we should use it in our applications, one of the reasons being that it helps us centralize exception handling and that we can implement it from normal classes without much boilerplate.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Effective error handling plays a crucial role in shaping the behavior of our applications. It involves establishing consistent response formats for our applications, ensuring a standardized approach even when errors occur. .NET 8 comes with the IExceptionHandler abstraction which offers us a new improved approach to handling errors in our applications. In this article, we&#8217;re [&hellip;]<\/p>\n","protected":false},"author":95,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[426,1811,957],"class_list":["post-103965","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-net-core-exception-handling","tag-c","tag-exception-handling","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2024-01-14T22:56:40+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Ainea Wabwoba\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Ainea Wabwoba\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\"},\"author\":{\"name\":\"Ainea Wabwoba\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/cbedf076f063c5db663e4e9ee05617af\"},\"headline\":\"How to Use IExceptionHandler to Handle Exceptions in .NET\",\"datePublished\":\"2024-01-14T22:56:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\"},\"wordCount\":1041,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET Core exception handling\",\"C#\",\"exception handling\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\",\"url\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\",\"name\":\"How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2024-01-14T22:56:40+00:00\",\"description\":\"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Use IExceptionHandler to Handle Exceptions in .NET\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/cbedf076f063c5db663e4e9ee05617af\",\"name\":\"Ainea Wabwoba\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/Ainea-Wabwoba-150x150.jpg\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/Ainea-Wabwoba-150x150.jpg\",\"caption\":\"Ainea Wabwoba\"},\"description\":\"Ainea is a software engineer with a background in .NET. He has experience developing and shipping solutions for small-scale and large-scale institutions across finance and agriculture. He also has a keen interest in cloud technologies which he researches and tinkers with. When not implementing solutions or writing, he's most probably out on a hike or swimming.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/in\/ainea-wabwoba\/\"],\"url\":\"https:\/\/code-maze.com\/author\/ainea-wabwoba\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze","description":"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/","og_locale":"en_US","og_type":"article","og_title":"How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze","og_description":"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.","og_url":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/","og_site_name":"Code Maze","article_published_time":"2024-01-14T22:56:40+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Ainea Wabwoba","twitter_card":"summary_large_image","twitter_creator":"@CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Ainea Wabwoba","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/"},"author":{"name":"Ainea Wabwoba","@id":"https:\/\/code-maze.com\/#\/schema\/person\/cbedf076f063c5db663e4e9ee05617af"},"headline":"How to Use IExceptionHandler to Handle Exceptions in .NET","datePublished":"2024-01-14T22:56:40+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/"},"wordCount":1041,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET Core exception handling","C#","exception handling"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/","url":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/","name":"How to Use IExceptionHandler to Handle Exceptions in .NET - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2024-01-14T22:56:40+00:00","description":"In this article, we will learn how to use IExceptionHandler interface to handle exception introduced in .NET 8.","breadcrumb":{"@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/dotnet-use-iexceptionhandler-to-handle-exceptions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Use IExceptionHandler to Handle Exceptions in .NET"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/cbedf076f063c5db663e4e9ee05617af","name":"Ainea Wabwoba","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/Ainea-Wabwoba-150x150.jpg","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/Ainea-Wabwoba-150x150.jpg","caption":"Ainea Wabwoba"},"description":"Ainea is a software engineer with a background in .NET. He has experience developing and shipping solutions for small-scale and large-scale institutions across finance and agriculture. He also has a keen interest in cloud technologies which he researches and tinkers with. When not implementing solutions or writing, he's most probably out on a hike or swimming.","sameAs":["https:\/\/www.linkedin.com\/in\/ainea-wabwoba\/"],"url":"https:\/\/code-maze.com\/author\/ainea-wabwoba\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103965","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/95"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=103965"}],"version-history":[{"count":1,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103965\/revisions"}],"predecessor-version":[{"id":103966,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/103965\/revisions\/103966"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=103965"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=103965"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=103965"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}