Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing Node apps.
We should handle errors centrally in our Node app.
For example, we can call next
in one middleware to call the error handling middleware that’s added after it.
We can write:
try {
User.addNew(req.body).then((result) => {
res.status(200).json(result);
}).catch((error) => {
next(error)
});
} catch (error) {
next(error);
}
to catch the error in the promise chain with the catch
method.
And with the try-catch block, we catch errors in the synchronous code.
Then we can add an error handler middleware after that code by writing:
app.use((err, req, res, next) => {
errorHandler.handleError(err).then((isOperationalError) => {
if (!isOperationalError)
next(err);
});
});
We invoke another promise chain to handle any operational errors.
These are errors that we can anticipate and handle gracefully.
API errors should be documented in some way so they can be handled.
We don’t want our app to crash.
Swagger lets us make document our APIs in an automated way.
If we don’t handle errors, then the app will crash.
#web-development #javascript #programming #nodejs