分子网络 API 网关。 onError 从不命中

moleculer-web API gateway. onError never hit

我们使用分子网站的示例作为我们 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 }))
      }
    }
 ]
}``

定义的functionThatCanThrowError是一个中间件。它应该是一个类似 Express 的中间件,你不能在其中抛出错误。为此,您应该调用 next(err).

例如:

const functionThatCanThrowError = async (req, res, next)=>{
    if (!req.body.email) {
      next(new BadRequestError('No email transferred.'))
    }
    ...
}

更多信息:https://expressjs.com/en/guide/error-handling.html

@icebob 所说的 + 一个例子


    module.exports = {
        name: "api",
        mixins: [ApiGateway],
        settings: {
            port: process.env.PORT || 3000,
            routes: [
                {
                    path: "/api",

                    whitelist: ["**"],

                    aliases: {
                        "GET /req-res-error": [
                            (req, res, next) => {
                                next(new MoleculerError("Req-Res Error"));
                            }
                        ],
                        "GET /action-error": "api.actionError"
                    },

                    onError(req, res, err) {
                        this.logger.error("An Error Occurred!");
                        res.end("Global error: " + err.message);
                    }
                }
            ]
        },

        actions: {
            async actionError() {
                throw new MoleculerError("ACTION ERROR");
            }
        }
    };