Practical Guide To Create REST API using Node.js and MS-Sql- Part IV

Hello everyone, let’s see how to handle errors and exceptions.

Error handling, Exceptions, Helper and more :

To deal with Errors and Exceptions we will create a file called exceptions.json in which we will store all the common exceptions we might get.

So, create this exceptions.json file inside config folder like this:

Here, we have just stored some basic error messages like Invalid Password, Unknown Error, and Duplicate Entry etc. with their HTTP Codes.

Now, create another new file as exception.js inside this config folder to handle these exceptions.

Here, we are using a class constructor to throw the error according to the parameters provided to it. This will match the error with our exceptions.json file and then return it back to the user.

The next, step is to use these files on app.js, defining a global variable, so that it can be available everywhere.

Now, create a new file helper.js inside utilities folder, where we will create a getExecption() method to throw the exception whenever it occurs.

Now again on app.js we will define a global variable for helper.js, so that it can be available everywhere.

And on response.js we will define sendError() method to return the error as response.

Now it is time to throw the Error from proudct class (product.js).

Here from the Catch block, we will call the above sendError() method.

Summary diagram:

Now, finally to check if it is working properly or not we can just provide the wrong Stored Procedure’s name so that we can get an exception.

So instead of ‘getAllProducts’ we can use ‘getAllProduct’ and then run this app and we can see the exception like this:

Jinal Shah is corporate trainer on different technology like node.Js, Angular,Ionic 2, BOT Framework etc.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store