I google for it and found some examples (like this).
I done everything like there, and all just fine!
But now every my router function contains try...catch block. Like that:
accounts = express.Router()
accounts.post('/following', async (req, res, next) => {
try {
***do some stuff***
if (smth_bad)
next(new ErrorHandler(413, 400, "Wrong data"));
} catch (e) {
next(e)
}
});
accounts.post('/followers', async (req, res, next) => {
try {
***do some stuff***
if (smth_bad)
next(new ErrorHandler(413, 400, "Wrong data"));
} catch (e) {
next(e)
}
});
accounts.post('/posts', async (req, res, next) => {
try {
***do some stuff***
if (smth_bad)
next(new ErrorHandler(413, 400, "Wrong data"));
} catch (e) {
next(e)
}
});
accounts.post('/pizza', async (req, res, next) => {
try {
***do some stuff***
if (smth_bad)
next(new ErrorHandler(413, 400, "Wrong data"));
} catch (e) {
next(e)
}
});
app.use('/api/v1/account', accounts);
app.use((err, req, res, next) => {
handleError(err, res);
});
I know, that i can use next() without try...catch, but I want to handle unexpected errors and tell about it to user. My handling looks like this:
class ErrorHandler extends Error {
constructor(statusCode, httpStatus, message) {
super();
this.statusCode = statusCode;
this.httpStatus = httpStatus;
this.message = message;
}
}
const handleError = (err, res) => {
if(err instanceof ErrorHandler){
const { statusCode, message, httpStatus } = err;
res.status(httpStatus).json({
status: "error",
statusCode,
message
});
} else {
console.error(err);
res.status(500).json({
status: "error",
statusCode: '510',
message: 'Server error',
});
}
};
Is there a way to simplify try...catch blocks in every router?