我们使用分子网站中的示例作为我们 API 网关的基础,并且在路由抛出错误时遇到问题 - onError
处理程序永远不会被命中,异常未处理并且节点使应用程序崩溃。不是这个主意!
我意识到这不是一个完整的例子,但如果我们犯了任何严重的概念错误,或者我们应该期望onError
处理程序被击中会很好...
const OpenApiMixin = require('./openapi.mixin')
const { MoleculerError } = require('moleculer').Errors
class BadRequestError extends MoleculerError {
constructor (message) {
message = message || 'Bad request'
super(message, 400, 'Bad request')
}
}
...
const functionThatCanThrowError = async (req, res)=>{
if (!req.body.email) {
throw new BadRequestError('No email transferred.')
}
...
}
module.exports = {
name: 'api-gateway',
mixins: [ApiGateway, OpenApiMixin()],
settings: {
...
path: '/',
routes: [
{
path: '/api',
...
aliases: {
'POST /route-can-throw-error': functionThatCanThrowError
},
// Route error handler
onError (req, res, err) {
let { type, code, message, data, name } = err
res.writeHead(Number(code) || 500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ type, code, message, data, name }))
}
}
]
}``