{"id":14214,"date":"2014-06-23T02:10:46","date_gmt":"2014-06-22T20:40:46","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=14214"},"modified":"2014-06-23T09:48:38","modified_gmt":"2014-06-23T04:18:38","slug":"defining-custom-errors-nodejs","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/defining-custom-errors-nodejs\/","title":{"rendered":"Defining custom errors &#8211; NodeJS"},"content":{"rendered":"<p>Any well written piece of code should be defensive by nature with defensive <strong>error handling<\/strong> understanding that things could go wrong. Things would be great if we can define our own <em><strong>custom error classes<\/strong><\/em> which we can pass or throw in order to distinguish various errors.\u00a0<strong>Custom error constructors helps in:<\/strong><\/p>\n<ul style=\"padding-left: 10px\">\n<li>\u21d2&nbsp;&nbsp; Identifying which error was thrown via compliance with <strong><em>instanceof<\/em><\/strong><\/li>\n<li>\u21d2&nbsp;&nbsp; Standardize\u00a0error message format and abstract message building at a central place making it more DRY.<\/li>\n<li>\u21d2&nbsp;&nbsp; Encapsulate additional data and information.<\/li>\n<li>\u21d2&nbsp;&nbsp; More readable, manageable and streamlined <em>Error Handling<\/em>.<\/li>\n<\/ul>\n<p><\/br><\/p>\n<h2 style=\"font-size:26px\">Building My Custom Error Class (Constructor)<\/h2>\n<p>Suppose we need to define a custom error named <strong>ValueOutOfRangeError<\/strong> which we will produce in case the values passed\/retrieved are not within a specific range.<\/p>\n<p>Lets see what all we need to do in order to define custom errors:<\/p>\n<h3>STEP 1: Make a file which will define the error.<\/h3>\n<p>Create a file with the name <strong>ValueOutOfRangeError.js<\/strong>. You can give any other name to the file, but its best recommended practice to name the file with the name of the constructor\/class they export.<\/p>\n<h3>STEP 2: Add a basic constructor function.<\/h3>\n<p>Make a constructor function which takes the desired arguments and sets the message property of the object. Then export it.<br \/>\n[javascript]<br \/>\n\/\/FILE ValueOutOfRangeError.js<br \/>\n&quot;use strict&quot;;<br \/>\n\/**<br \/>\n * Error Class ValueOutOfRangeError<br \/>\n * *\/<br \/>\nfunction ValueOutOfRangeError(propertyName, actualValue, rangeMin, rangeMax) {<br \/>\n    \/\/Set the name for the ERROR<br \/>\n    this.name = this.constructor.name; \/\/set our function\u2019s name as error name.<\/p>\n<p>    \/\/Define error message<br \/>\n    this.message = [<br \/>\n                     &quot;Property with name |&quot;,<br \/>\n                      propertyName ,<br \/>\n                      &quot;| contains the value&quot;,<br \/>\n                      actualValue,<br \/>\n                      &quot;which is outside the range:&quot;,<br \/>\n                      rangeMin, &quot;to&quot;, rangeMax<br \/>\n                   ].join(&quot; &quot;); \/\/Concat and make a string.<br \/>\n}<\/p>\n<p>\/\/Export the constructor function as the export of this module file.<br \/>\nexports = module.exports = ValueOutOfRangeError;<\/p>\n<p>[\/javascript]<\/p>\n<h3>STEP 3: Inherit from native Error class.<\/h3>\n<p>Lets inherit from the <strong>Error<\/strong> native constructor such that our new custom error constructor is an actual error object.<br \/>\n[javascript]<br \/>\n\/\/FILE ValueOutOfRangeError.js<br \/>\n&quot;use strict&quot;;<\/p>\n<p>\/\/Utils module loaded<br \/>\nvar util = require(&#8216;util&#8217;);<\/p>\n<p>\/**<br \/>\n * Error Class ValueOutOfRangeError<br \/>\n * *\/<br \/>\nfunction ValueOutOfRangeError(propertyName, actualValue, rangeMin, rangeMax) {<\/p>\n<p>    \/*INHERITANCE*\/<br \/>\n    Error.call(this); \/\/super constructor<br \/>\n    Error.captureStackTrace(this, this.constructor); \/\/super helper method to include stack trace in error object<\/p>\n<p>    \/\/Set the name for the ERROR<br \/>\n    this.name = this.constructor.name; \/\/set our function\u2019s name as error name.<\/p>\n<p>    \/\/Define error message<br \/>\n    this.message = [<br \/>\n                     &quot;Property with name |&quot;,<br \/>\n                      propertyName ,<br \/>\n                      &quot;| contains the value&quot;,<br \/>\n                      actualValue,<br \/>\n                      &quot;which is outside the range:&quot;,<br \/>\n                      rangeMin, &quot;to&quot;, rangeMax<br \/>\n                   ].join(&quot; &quot;); \/\/Concat and make a string.<br \/>\n}<\/p>\n<p>\/\/ inherit from Error<br \/>\nutil.inherits(ValueOutOfRangeError, Error);<\/p>\n<p>\/\/Export the constructor function as the export of this module file.<br \/>\nexports = module.exports = ValueOutOfRangeError;<\/p>\n<p>[\/javascript]<\/p>\n<h3>STEP 4: Yeahh! All done. We have our first custom-error file in place:).<\/h3>\n<h2 style=\"font-size:26px\">Using the custom-errors!<\/h2>\n<p>Now lets see how we can use our <strong>ValueOutOfRangeError<\/strong> class which we defined above.<br \/>\n[javascript]<br \/>\n\/\/Load the custom error.<br \/>\nvar ValueOutOfRangeError = require(&quot;.\/ValueOutOfRangeError&quot;);<\/p>\n<p>\/\/THROWING EXAMPLE<br \/>\nif(\/*error check fails*\/) throw new ValueOutOfRangeError(&quot;theAwesomeProperty&quot;, data.theAwesomeProperty, 10, 100);<\/p>\n<p>\/\/EXAMPLE RETURN VALUE<br \/>\nif(\/*error check fails*\/) callback(new ValueOutOfRangeError(&quot;theAwesomeProperty&quot;, data.theAwesomeProperty, 10, 100));<\/p>\n<p>[\/javascript]<\/p>\n<p>Hope that helps!! \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Any well written piece of code should be defensive by nature with defensive error handling understanding that things could go wrong. Things would be great if we can define our own custom error classes which we can pass or throw in order to distinguish various errors.\u00a0Custom error constructors helps in: \u21d2&nbsp;&nbsp; Identifying which error was [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0},"categories":[1185],"tags":[1447,55,1156,1124,1177],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/14214"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=14214"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/14214\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=14214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=14214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=14214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}