0

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

2 回答 2

3

定义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

于 2020-02-07T14:54:55.500 回答
2

@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");
            }
        }
    };

于 2020-02-07T15:32:50.903 回答