Error handling is not the most attractive part of coding efforts, but it is absolutely necessary to build reliable, production-level applications in it. Errors can cause application crashes, expose vulnerabilities, or cause user dissatisfaction.
1. try-catch
For synchronization operations intry-catch
It is your first choice. It allows you to intercept errors in a controlled way, preventing application crashes.
Example:
const fs = require('fs');function readJSONFile(filePath) { try { const data = (filePath, 'utf8'); return (data); } catch (error) { ("An error occurred while reading or parsing a file:", ); throw new Error("Invalid JSON data"); // Rethrow it and let the caller handle it. } }
Why this matters:
- It manages errors gracefully and keeps the application running.
- Since you can log and track problems, it makes debugging easier.
hint: Log errors so that you can provide more context when debugging.
2. Global Error Handler
There is oneMechanism used to handle global errors such as unhandled rejections or exceptions.
Example:
('uncaughtException', (error) => { ("Uncaught exception:", ); // Log errors, clean up resources, and exit if necessary. (1); }); ('unhandledRejection', (reason, promise) => { ("Unhandled Rejection:", promise, "reason:", reason); });
Why this matters:
- Prevent application crashes due to unexpected problems.
- Add the last line of error monitoring.
warn: Use with caution. Over-reliance on global processors can mask deeper issues.
3. Use middleware to handle errors in Express
If you are using Express to build an API or web server, middleware is the cleanest way to handle errors. You can centralize error handling logic instead of repeating it everywhere.
Example:
const express = require('express'); const app = express(); // Custom error middleware((err, req, res, next) => { ("An error occurred:", ); ( || 500).json({ error: }); }); // Sample routing('/', (req, res) => { throw new Error("There's an error!"); }); // Middleware to catch all errors((err, req, res, next) => { (500).send('Internal Server Error'); }); (3000, () => ("The server runs on port 3000"));
Why this matters:
- Neat and reusable logic.
- Keep it simple and focus on business logic.
4. Use the library for error handling
pictureBoomorhttp-errorsSuch a library simplifies error prompts.
Examples of using Boom:
const Boom = require('@hapi/boom'); // Create and throw an errorfunction fetchUser(id) { if (!id) { throw ("User ID is required."); } // Get logic} // Error handling in Express((err, req, res, next) => { if ((err)) { ().json(); } else { (500).json({ message: "An unexpected error occurred" }); } });
Why this matters:
- Reduced boilerplate code for common error scenarios.
- Provides structure for consistent API responses.
Some extra tips:
- Recording errors:useWinstonorPinoand other tools to effectively manage logs.
- Don't overuse try-catch: Use it where errors are expected, rather than everywhere.
- Test your error path: Simulation failed during development to see if your error handling can stand the test.
- Monitor with APM tools: Integrate monitoring solutions such as New Relic or Sentry to capture errors in production environments.
Summarize
Handling errors in is not just to avoid application crashes, but also to build a predictable, robust and easy-to-maintain system. By implementing this technique above, you can monitor errors and provide a smoother user experience.
This is the article shared by this article about the 4 best ways to deal with errors. For more related errors, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!