gpt4 book ai didi

error-handling - Express 路由中的错误处理

转载 作者:行者123 更新时间:2023-12-03 07:50:32 25 4
gpt4 key购买 nike

我有一个包装 RESTful API 的 Node 模块。这个客户端遵循标准的节点回调模式:

module.exports = { 
GetCustomer = function(id, callback) { ...}
}

我从各种 Express 路由中调用该客户端,如下所示:
app.get('/customer/:customerId', function(req,res) {
MyClient.GetCustomer(customerId, function(err,data) {
if(err === "ConnectionError") {
res.send(503);
}
if(err === "Unauthorized") {
res.send(401);
}
else {
res.json(200, data);
}
};
};

问题是我认为每次调用此客户端时检查“ConnectionError”并不是干的。我不相信我可以调用 res.next(err)因为这将作为 500 错误返回。

我在这里缺少节点或 Javascript 模式吗?在 C# 或 Java 中,我会在 MyClient 中抛出适当的异常。

最佳答案

您想创建错误处理中间件。这是 Express 的一个示例:https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

这是我使用的:

module.exports = function(app) {

app.use(function(req, res) {
// curl https://localhost:4000/notfound -vk
// curl https://localhost:4000/notfound -vkH "Accept: application/json"
res.status(404);

if (req.accepts('html')) {
res.render('error/404', { title:'404: Page not found', error: '404: Page not found', url: req.url });
return;
}

if (req.accepts('json')) {
res.send({ title: '404: Page not found', error: '404: Page not found', url: req.url });
}
});

app.use( function(err, req, res, next) {
// curl https://localhost:4000/error/403 -vk
// curl https://localhost:4000/error/403 -vkH "Accept: application/json"
var statusCode = err.status || 500;
var statusText = '';
var errorDetail = (process.env.NODE_ENV === 'production') ? 'Sorry about this error' : err.stack;

switch (statusCode) {
case 400:
statusText = 'Bad Request';
break;
case 401:
statusText = 'Unauthorized';
break;
case 403:
statusText = 'Forbidden';
break;
case 500:
statusText = 'Internal Server Error';
break;
}

res.status(statusCode);

if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
console.log(errorDetail);
}

if (req.accepts('html')) {
res.render('error/500', { title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
return;
}

if (req.accepts('json')) {
res.send({ title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
}
});
};

关于error-handling - Express 路由中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com