NodeJS - Exception Handling in eventful Code

Node.jsServer Side ProgrammingProgramming

<p>An exception is a type of an event, that occurs while executing or running a program that stops the normal flow of the program and returns to the system. When an exception occurs the method creates an object and gives it to the runtime system. This creating an exception and giving it to the runtime system is known as <em>throwing an Exception</em>.</p><p>We need to handle these Exceptions to handle any use case and prevent the system from crashing or performing an unprecedented set of instructions. If we donot handle or throw exceptions, the program may perform strangely.</p><h2>Exception handling in Synchronous Program</h2><p>Here, we will learn how to handle exceptions in a eventful flow of program. In an eventful flow of program, an error can occur anywhere. Therefore, instead of throwing the error, you need to fire the error event instead.</p><h2>Example</h2><!--<p><a href="" target="_blank" rel="nofollow" class="demo"><i class="fa-external-link"></i> Live Demo</a></p>--><pre class="prettyprint notranslate">// Definite our Divide Number Event var events = require(&quot;events&quot;) var DivideNumber = function(){ &nbsp; &nbsp;events.EventEmitter.call(this) } require(&#39;util&#39;).inherits(DivideNumber, events.EventEmitter) // Add the divide function DivideNumber.prototype.divide = function(x, y){ &nbsp; &nbsp;// if error condition occurs ? &nbsp; &nbsp;if ( y === 0 ) { &nbsp; &nbsp; &nbsp; // &quot;throw&quot; the error safely by emitting it &nbsp; &nbsp; &nbsp; var err = new Error(&quot;Can&#39;t divide by zero&quot;) &nbsp; &nbsp; &nbsp; this.emit(&quot;error&quot;, err) &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; // If No error occurrs, return the result &nbsp; &nbsp; &nbsp; this.emit(&quot;Number divided&quot;, x, y, x/y) &nbsp; &nbsp;} &nbsp; &nbsp;// Return the event chain &nbsp; &nbsp;return this; } // Create our divider and listen for errors var divideNo = new DivideNumber() divideNo.on(&#39;error&#39;, function(err){ &nbsp; &nbsp;// handle the error safely &nbsp; &nbsp;console.log(err) }) divideNo.on(&#39;Number divided&#39;, function(x, y, result){ &nbsp; &nbsp;console.log(x+&quot;/&quot;+y+&quot;=&quot;+result) }) // Dividing the number divideNo.divide(10, 5).divide(10, 0)</pre><h2>Output</h2><p><img src="https://www.tutorialspoint.com/assets/questions/media/51661/eventful.jpg" class="fr-fic fr-dib" width="600" height="216"></p>
raja
Updated on 28-Apr-2021 06:22:07

Advertisements