Global ERROR Handlers and Custom ERRORS
Mon Mar 18 2024 03:11:06 GMT+0000 (Coordinated Universal Time)
Saved by
@Marcelluki
Global Error Handlers and Custom Errors
Sometimes, despite all our efforts, some errors may still go unhandled, our code will fail, and the application will crash. Fortunately, Node.js has a mechanism to deal with this. Meet global error handlers.
Global error handlers
To add a global error handler, we'll subscribe to the uncaughtException event of the built-in process module.
You can implement your own logic to handle errors. However, for now, we'll focus on logging information about errors to the console.
The code for implementing a global handler looks like this:
const process = require('process');
process.on('uncaughtException', (err, origin) => {
console.log(`${origin} ${err.name} with the message ${err.message} was not handled. Pay attention to it!`);
});
// Throw a synchronous error
throw new Error(`The missed error`);
This handler catches errors in both synchronous functions and promises. You can see this if you replace throw with Promise.reject(...).
We can determine where the error occurred by referring to the value stored in the origin parameter of the handler function. If its value is unhandledRejection, this means an error occurred in the promise. Otherwise, it means it was thrown using throw.
Defining custom errors in JavaScript
Engineers often need to extend the Error object to include additional information necessary for handling errors. For example, we may have a situation where we need to set our own error name or indicate the response status code we want to be sent to the user.
Since errors are normal objects, we can do this manually. All we need to do is specify the desired information as a property of a specific error instance.
However, in practice, engineers usually define custom error classes by extending the standard Error class. By reusing code, engineers prevent code duplication.
Let's describe your first custom error: a data validation error:
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
this.statusCode = 400;
}
}
We simply extended the standard Error class by setting the values of the name and statusCode fields in the constructor. In the future, we'll need the name field to determine the type of error.
You can use your own error in the same way you'd use a standard one, for example: throw new ValidationError("A validation error occurred").
Different problems require different handling scenarios, so it is important to be able to distinguish between different types of errors. We'll talk about how to do this in the next lesson.
content_copyCOPY
https://tripleten.com/trainer/web/lesson/600d6e0b-1367-49cd-8934-923171247549/
Comments