Node.js – Errors – How do we handle errors (Error handling)?

Errors occur when something went wrong, during the Program execution. There are different types of errors and these should be handled properly in the program to avoid abnormal program termination.

Node.js provides different ways to handle the errors generated while running the Applications in Node.js run-time environment. We can handle the errors using try..catch constructs, which is a standard way of handling errors in JavaScript; or we can use Error event handler; or we can also use callback methods to handle the errors. We have discussed about Events in our previous article “Node.js – Events – A brief discussion“. I recommend you to read the article, before you attempt to handle the error through Events.

So, which mechanism we use to handle these errors? This depends on the type of error we get. Normally, we categorize the errors which occur during the execution of a Program in Node.js run-time environment as; System errors, JavaScript errors, User-defined errors and assertion errors.

System errors are generated by the Operating System. JavaScript errors are generated when something wrong in JavaScript program. User-defined errors are defined within the Program. And Assertion errors occur when Node.js detects a wrong logic in the Program.

EventEmitter class object emits the error events when an error occurs and the attached listeners should handle the events. Otherwise, an error is thrown and the Application exits.

A JavaScript Error object captures the stack trace information and it is more useful to resolve the errors.

</> Michael

Add a Comment

Your email address will not be published.