Kha*_*bib 3 javascript error-handling node.js express
我正在使用 Express 开发 Node.js 来构建后端。我打算处理可能发生的状态 500 错误。
router.put('/test', async (req, res) => {
try {
return res.send(await request.updateTest(req.body, 1))
} catch(err) {
console.log(err)
return res.status(500).send(err.stack)
}
})
Run Code Online (Sandbox Code Playgroud)
这是我的代码示例。它工作得很好。但是当我尝试从数据库查询中发出未知错误时,我想记录错误并返回状态 500 作为带有错误详细信息的响应。
但每次构建新的控制器/路由时我都需要添加 try 和 catch
无论如何,我可以以中间件的形式表达它们,而不是每次都写 try 和 catch 吗?
这是我尝试将其作为中间件的代码示例,但它在调用时不起作用且没有效果。
错误.js
module.exports = function (err, req, res, next) {
console.log(err)
res.status(500).send({
error: 'Internal Server Error',
message: err.stack
})
next(err)
}
Run Code Online (Sandbox Code Playgroud)
main.js
const errorHandler = require('./error')
const { corsOption } = require('./cors')
const cors = require('cors')
const test = require('./test')
module.exports = function (app) {
app.use(cors(corsOption))
app.use(errorHandler)
app.use('/api/test', test)
}
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以做些什么来使其发挥作用吗?
您的全局错误处理程序应放置在所有其他中间件/路由之后:
app.use(middleware)
// all other middlewares
app.use('/api/test', test)
// all other routes
// error handler
app.use(function (err, req, res, next) {
res.status(500).json({
error: err.message,
});
});
Run Code Online (Sandbox Code Playgroud)
为了避免向所有内容添加 try/catch,最好包装路由处理程序以捕获错误(asyncWrapper):
app.use(middleware)
// all other middlewares
const asyncWrapper = (cb) => {
return (req, res, next) => cb(req, res, next).catch(next);
};
const test = async (req, res) => {
return res.send(await request.updateTest(req.body, 1))
}
// wrap your handler to catch errors (Async functions return a promise)
app.use('/api/test', asyncWrapper(test))
// all other routes
// error handler
app.use(function (err, req, res, next) {
res.status(500).json({
error: err.message,
});
});
Run Code Online (Sandbox Code Playgroud)