我创建了nodejs + Express应用程序。现在在我的应用程序中,当异常捕获错误时发送如下
app.get('/data', (req, res) => {
if(!req.params.token){
return res.status(403).send('Access token not provided');
}
//do something here
});
我可以发送这样的内容,而不是发送res.status(403).send('Access token notprovided');
异常.js
class Forbidden {
constructor(message,stack = null){
this.code = 403;
this.message = message
this.stack = stack;
}
}
app.js
var httpForbidden = require('exception.js');
app.get('/data', (req, res) => {
if(!req.params.token){
return new httpForbidden ('Access token not provided');
}
//do something here
});
我怎样才能在一个地方捕获所有异常?
最佳答案
你可以使用这样的东西:
class httpError {}
class httpForbidden extends httpError {
constructor(message, stack = null) {
super();
this.code = 403;
this.message = message
this.stack = stack;
}
}
app.get('/', (req, res) => {
if (!req.params.token) {
throw new httpForbidden('Access token not provided');
}
...
});
app.use((err, req, res, next) => {
if (err instanceof httpError) {
return res.status(err.code).send(err.message);
}
res.sendStatus(500);
});
这使用 Express error handling middleware它将检查抛出的错误是否是 httpError
的实例(这将是您想要创建的所有 HTTP 错误类的父类(super class)),如果是,将生成一个特定的根据代码和消息进行响应(否则生成通用 500 错误响应)。
关于node.js - NodeJs http状态异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280569/