<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Exception Handling Archives - Blog IT</title>
	<atom:link href="https://blogit.create.pt/tag/exception-handling/feed/" rel="self" type="application/rss+xml" />
	<link>https://blogit.create.pt/tag/exception-handling/</link>
	<description>Create IT blogger community</description>
	<lastBuildDate>Fri, 30 Oct 2020 15:23:31 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>
	<item>
		<title>How to Handle known Exceptions?</title>
		<link>https://blogit.create.pt/diogocoelho/2020/10/22/how-to-handle-known-exceptions/</link>
					<comments>https://blogit.create.pt/diogocoelho/2020/10/22/how-to-handle-known-exceptions/#respond</comments>
		
		<dc:creator><![CDATA[Diogo Coelho]]></dc:creator>
		<pubDate>Thu, 22 Oct 2020 18:11:58 +0000</pubDate>
				<category><![CDATA[Design/Integration Patterns]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[Exception Handling]]></category>
		<guid isPermaLink="false">https://blogit.create.pt/?p=12069</guid>

					<description><![CDATA[<p>This post will describe several ways to handle known Exceptions in a project. For each possible implementation, we will do an overview of the flow that the exception does to understand the context of each implementation. First, let’s do an overview of what is, normally, a basic flow in any Project. The basic flow of [&#8230;]</p>
<p>The post <a href="https://blogit.create.pt/diogocoelho/2020/10/22/how-to-handle-known-exceptions/">How to Handle known Exceptions?</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This post will describe several ways to handle known <strong>Exceptions </strong>in a project.</p>



<p>For each possible implementation, we will do an overview of the flow that the exception does to understand the context of each implementation.</p>



<p>First, let’s do an overview of what is, normally, a basic flow in any Project.</p>



<h2 class="wp-block-heading">The basic flow of an API Project</h2>



<h2 class="wp-block-heading"></h2>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" src="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow-1.png" alt="" class="wp-image-12086" width="1064" height="641" /></figure>



<p><em>The previous Figure shows the basic flow of events inside the IDM project. The API receives an HTTP Request in a certain endpoint. The endpoints of the API are mapped in the controller layer, so when the API receives the HTTP request the controller is the first to interact with that request and sends that request to the respective service that will orchestrate all the necessities of that request. Those necessities could be, for example, retrieve some information from the Database, and that is done in the repository layer. The repository layer is where we map all the interactions with external services(DataBases, API, etc). This is a basic overview of what could be a basic API project.</em></p>



<h2 class="wp-block-heading">The Exception Handling Problem</h2>



<p>Taking into account the previous overview of the project, we want to make the process of handling exceptions the more clearest and efficient possible in terms of computational needs, but also in terms of code structure. To achieve this purpose we will describe three different ways of handling the exceptions.</p>



<p>Also, in this project, we have 2 different types of exceptions. They are:</p>



<ul class="wp-block-list"><li>DomainException &#8211; This is the type of exception that is thrown when the error that happens is something that the API already expects;</li><li>Exception &#8211; This could actually be any type of exception different from DomainException. This occurs when an unexpected error occurs in the API;</li></ul>



<h5 class="wp-block-heading">Reference to Middleware</h5>



<p>In this case, we will use the <strong>ExceptionHandler </strong>middleware layer. The middleware layer is specific to .NET Core and we will not focus on that here. Take into account that we will use <strong>ExceptionHandler </strong>in the middleware pipeline to catch all the exceptions that are not treated.</p>



<p>Here is the reference to <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1">ASP.NET Core Middleware</a>.</p>



<h2 class="wp-block-heading">First Approach: Try-Catch on Controller Layer</h2>



<p>This approach consists of catching and treating the DomainExceptions that are thrown by any of the layers (Controller, Service, or Repository) of the APIProject in the Controller layers. Take into account that all the unexpected exceptions are always treated in the ExceptionHandler of the Middleware.</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_FirstApproachV2-1.png" alt="" class="wp-image-12085" width="1064" height="1071" /></figure>



<h2 class="wp-block-heading">Second Approach: Try-Catch in all Layers</h2>



<p>This approach consists of all layers of the API Project being capable of catching exceptions and sending again the exception to the upper layers. The Controller layer is where the Domain Exceptions will be treated.</p>



<p>Take into account that in this case, the unexpected exceptions are caught by the layer that throws her and also by the rest of the upper layers. However, it is treated in the ExceptionHandler of the Middleware.</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_SecondApproach-1.png" alt="" class="wp-image-12084" width="1067" height="1095" /></figure>



<h2 class="wp-block-heading">Third Approach: Encapsulate Exception in Response Object</h2>



<p>This approach consists, as the name says, in encapsulating the exception in the Response Object. Instead of throwing the exception, we will send the Response object with a Failed message with an instance of the exception in the Response Object as a variable. This means that the system will not need to operate the throws of exceptions for the expected errors. They will be passed in the response object.</p>



<p>Take into account that only the unexpected exceptions are thrown to Middleware &#8211; <strong>ExceptionHandler </strong>to be treated.</p>



<p></p>



<h4 class="wp-block-heading" id="Normal-Response-Object">Normal Response Object</h4>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class OperationResult
{
        public OperationResult();

        public static OperationResult Success { get; }
        public bool Succeeded { get; protected set; }
        public IEnumerable&lt;OperationError&gt; Errors { get; }

        public static OperationResult Failed(params OperationError&#x5B;] errors);
        public override string ToString();
}
</pre></div>


<h4 class="wp-block-heading" id="New-Response-Object-for-this-approach">New Response Object for this approach</h4>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: vb; title: ; notranslate">
public class OperationResult
{
        public OperationResult();
           
        public static OperationResult Success { get; }
        public bool Succeeded { get; protected set; }
        public IEnumerable&lt;OperationError&gt; Errors { get; }

        public static OperationResult Failed(params OperationError&#x5B;] errors);
        public override string ToString();
        public Exception ExceptionHolder { get; set;} 
}
</pre></div>


<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_ThirdApproach-2.png" alt="" class="wp-image-12083" width="1067" height="1061" /></figure>



<h2 class="wp-block-heading">Fourth Approach: Catch all exceptions in Middleware &#8211; Exception Handler</h2>



<p>The approach consists of throwing the exceptions whenever they happen and then let them be caught and treated by the middleware &#8211; ExceptionHandler. In this approach, we would create a different type of response for each type of exception for the ExceptionHandler send as Response.</p>



<p>This would centralize all the exception handling in one place.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="682" height="671" src="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_FourthApproach-7.png" alt="" class="wp-image-12117" srcset="https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_FourthApproach-7.png 682w, https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_FourthApproach-7-300x295.png 300w, https://blogit.create.pt/wp-content/uploads/2020/10/ControllerServiceRepositoryFlow_FourthApproach-7-427x420.png 427w" sizes="(max-width: 682px) 100vw, 682px" /></figure>



<p></p>



<h2 class="wp-block-heading">Comparison of Exception Handling approaches</h2>



<figure class="wp-block-table is-style-regular"><table><tbody><tr><th><strong>Exception Handling Approach</strong></th><th><strong>Pros</strong></th><th><strong>Cons</strong></th></tr><tr><td>First Approach: Try-Catch on Controller Layer</td><td>One place to treats the expected exceptions and another for the unexpected;<br><br>No need to make calls to the error page when is an expected error, thus making the operation quicker;<br><br>Only adds exception related code in the controller Layer;<br></td><td>Catch &amp; Throw of exception in the controller layer uses more computational resources;<br><br>Every endpoint mapped in the controller will need try-catch;</td></tr><tr><td>Second Approach: Try-Catch in all Layers</td><td>Easy to know where the exception happened and where it is (easy to understand the flow);<br><br>One place to treats the expected exceptions and another for the unexpected;</td><td>Exception handling code everywhere;<br><br>Can cause a bottleneck in the app because of the inherent addition of time to the response and use of computational resources;<br><br>Repeated Code;<br><br>Make logical code harder to understand;<br></td></tr><tr><td>Third Approach: Encapsulate Exception in Response Object</td><td>The runtime doesn’t need to handle the throw of expected Exceptions;<br><br>One place to treats the expected exceptions (in this case inside the response Object) and another for the unexpected;<br><br>App maintains a normal flow even to it occurred an expected exception;<br></td><td>Handling of the expected exceptions is not explicit;</td></tr><tr><td>Fourth Approach: Catch all exceptions in Middleware &#8211; Exception Handler</td><td>Aggregates the handling of all exceptions in one place;<br><br>Exception handling code is in one place and logical/business code in other;</td><td>Unexpected and Expected exceptions handling are in the same place;<br><br>Add another request to the operation because it will always need to request the errors page when an exception happens (Middleware- Exception Handler Implementation);<br></td></tr></tbody></table><figcaption></figcaption></figure>



<p></p>
<p>The post <a href="https://blogit.create.pt/diogocoelho/2020/10/22/how-to-handle-known-exceptions/">How to Handle known Exceptions?</a> appeared first on <a href="https://blogit.create.pt">Blog IT</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogit.create.pt/diogocoelho/2020/10/22/how-to-handle-known-exceptions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
