【问题标题】:HapiJS error handlingHapiJS 错误处理
【发布时间】:2017-09-22 19:29:44
【问题描述】:

我创建了这样的错误实例:

class InsufficientScope extends Error {
  constructor(resource = false) {
    const errorMessage = resource
      ? 'User does not have enough privileges to access this resource.'
      : `User does not have enough privileges to access the ${resource}`;

    super(errorMessage);

    this.type = 'authorization_error';
    this.statusCode = '403';
  }
}

当我在我的处理程序中抛出这些错误(如 return reply(new InsufficientScope());)时,它总是以某种方式转换为 Boom 对象。是否在 Hapi 中抛出的每个错误都转换为具有其属性的 Boom 对象?

因为我希望能够通过 onPreResponse 扩展点指定某些特定错误的行为(即记录是/否等)。但我无法真正区分这是我自己的错误还是 Hapi 引发的错误,因为它们看起来都一样。

我也不能这样做:

if (req.response instanceof InsufficientScope) {
 // do something
}

我也不能使用Boom.create,因为那不是一个实例,而只是一个普通对象。

【问题讨论】:

    标签: javascript hapijs


    【解决方案1】:

    你可以通过两种方式做到这一点
    1)回复(null,new InsufficientScope())
    2)onPreresponse钩子你可以这样做

    server.ext('onPreResponse', (request, reply) => {
      if((request.response.isBoom)
      {
       return reply(null,new InsufficientScope())
       }
      return reply.continue();
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多