In Node.js, promises can be rejected for various reasons such as errors during database operations or network issues. Handling promise rejections is crucial to ensure that your application doesn't crash unexpectedly and provides a useful error message to the user.
Below are some basic strategies you can use to handle promise rejections:
-
Catching Promises: Use the
catch
method on a promise to catch its rejection. This method is especially useful when writing async code that uses promises.
// Example of catching a promise
somePromise()
.then(value => {
console.log(value); // Logs the resolved value
})
.catch(error => {
console.error('Error:', error); // Logs the rejection reason
});
-
Using Finally: The
finally
method allows you to run some code after a promise is either resolved or rejected, regardless of its outcome. It's useful for performing cleanup tasks like closing database connections or streams.
// Example of using finally
somePromise()
.then(value => {
console.log(value); // Logs the resolved value
})
.catch(error => {
console.error('Error:', error); // Logs the rejection reason
})
.finally(() => {
// Cleanup code here, runs regardless of promise outcome
console.log('Cleaning up...');
});
-
Using Async/Await: If you're using ES6 or later and your environment supports async/await, you can use a try-catch block to catch exceptions thrown inside an
async
function:
// Example of using async/await with try-catch
async function example() {
try {
let value = await somePromise();
console.log(value); // Logs the resolved value
} catch (error) {
console.error('Error:', error); // Logs the rejection reason
}
}
example();
-
Custom Error Handling: Create custom errors by extending JavaScript's built-in
Error
class and throwing them from your promise rejections. This can help you differentiate between different types of failures in your application.
class CustomError extends Error {
constructor(message, code) {
super(message);
this.name = 'CustomError';
this.code = code;
}
}
// Example of throwing a custom error from promise rejection
somePromise()
.then(value => {
console.log(value); // Logs the resolved value
})
.catch(error => {
if (error instanceof CustomError) {
console.error('Custom Error:', error.message, 'Code:', error.code);
} else {
console.error('Unexpected Error:', error); // Logs the rejection reason
}
});
Remember that promise rejections are considered exceptional scenarios and should not be relied upon as a normal part of your program flow. They should be treated like failures, and handled appropriately to provide better user experience and maintain the robustness of your application.