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 the Node.js run-time environment. We can handle the errors using try..catch
constructs, which is a standard way of handling errors in JavaScript; we can use an Error event handler; or we can also use callback methods to handle the errors. We have discussed Events in our previous article “Node.js – Events – A brief discussion“. I recommend you read the article before you attempt to handle the error through Events.
So, which mechanism do 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 the 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 is wrong in the 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 errors.
</> Michael