我们使用来自 molecularr 网站的示例作为 API 网关的基础,并且当路由抛出错误时会遇到问题 - onError
处理程序永远不会被命中,异常未得到处理并且 Node 使应用程序崩溃。不是这个主意!
我意识到这不是一个完整的示例,但如果我们犯了任何严重的概念错误,或者如果我们应该期望 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 }))
}
}
]
}``
最佳答案
定义的functionThatCanThrowError
是一个中间件。它应该是一个类似 Express 的中间件,你不能在其中抛出错误。为此,您应该调用 next(err)
。
例如:
const functionThatCanThrowError = async (req, res, next)=>{
if (!req.body.email) {
next(new BadRequestError('No email transferred.'))
}
...
}
关于node.js - molecularr-web API 网关。 onError 从未命中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60113056/