Javascript 在express中尝试使用catch block
我在谷歌上搜索了一下,找到了一些例子(比如) 我在那里做了所有的事情,一切都很好 但现在每个my router函数都包含try…catch块。就像这样:Javascript 在express中尝试使用catch block,javascript,node.js,express,try-catch,Javascript,Node.js,Express,Try Catch,我在谷歌上搜索了一下,找到了一些例子(比如) 我在那里做了所有的事情,一切都很好 但现在每个my router函数都包含try…catch块。就像这样: accounts = express.Router() accounts.post('/following', async (req, res, next) => { try { ***do some stuff*** if (smth_bad) next(new Erro
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);
});
我知道,我可以不使用try…catch就使用next(),但我想处理意外错误并将其告知用户。我的处理方式如下所示:
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',
});
}
};
有没有办法简化每个路由器中的try…catch块 首先,try/catch不会异步捕获错误。如果try/catch中的所有代码都是同步的,那么您所做的工作就会起作用,但正如您已经发现的,这是解决问题的一种非常麻烦的方法 有很多方法可以做到这一点,但我认为也许你应该问一个不同的问题:“好的模块化代码是什么样子的?”或者“如何在代码中实现路由器?” 我建议你去寻找如何构造路由器的模式 一种可能的方法是编写在try/catch块外部定义的函数(为了整洁起见,可能在另一个模块中定义),并在try/catch内部使用它们。像这样:
const getStuffFunction = function(req,callback){
//do stuff here
}
accounts.post('/pizza', async (req, res, next) => {
getStuffFunction(req,function(){
//do router stuff here after your business logic is done
})
希望有帮助