moleculer-web API网关。 onError从未命中

问题描述 投票:0回答:2

[我们使用了Molecularr网站上的示例作为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 }))
      }
    }
 ]
}``
node.js api-gateway moleculer moleculer-web
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

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

© www.soinside.com 2019 - 2024. All rights reserved.