有人能向我解释一下下面代码Express JS中异常错误处理的两种方法之间的区别吗:
const express = require('express');
const app = express();
app.get('/test', (req, res, next) => {
// the first way:
throw new Error('my error message');
// the second way:
next(new Error('my error message'));
});
app.use((err, req, res, next) => {
res.status(err.status || 500).send(err.message || 'Internal Server Error');
});
app.listen(3000, () => console.log('Welcome to ExpressJS'));
它返回由错误中间件处理的相同结果,但这里有什么区别?
Nothing,基于源代码。
try {
fn(req, res, next);
} catch (err) {
next(err);
}
我偶然发现了一个场景,在这个场景中,下一个函数对我来说是有意义的。我创建了一个中间件来检查快速路由中所需的参数,当我遇到两个或多个所需参数不满足的情况时,抛出错误会在第一个错误时停止请求。对于下一个函数,它不会在第一个错误时停止,实际上我收到了消息,通知我需要满足的所有参数,这正是我想要做的。代码片段:
export const validateParams = (params: string[]) => {
return async (request: Request, response: Response, next: NextFunction) => {
try {
for (const field of params) {
if (!request.body[field]) {
next(new MissingParamError(field))
// instead of
// throw new MissingParamError(field)
}
}
return next()
} catch (error) {
if (error instanceof Error) return response.status(400).send(error.message);
}
};
};