happy 不会从 Boom 错误返回数据属性

Hapi does not return data attribute from Boom error

本文关键字:错误 返回 数据属性 Boom happy      更新时间:2023-09-26

当回复我的快乐路线的繁荣错误时......

{
      method: 'PUT',
      path:'foo',
      handler: function (request, reply) {
        reply(Boom.badRequest('something', { stuff: 'and more' }));
      }
}

。我得到以下响应:

{"statusCode":400,"error":"Bad Request","message":"something"}

它缺少提供错误详细信息的数据对象! 怎么回事?

在快乐的文档中,它引用了 boom 对象上的 output.payload 属性,默认情况下设置为包括 statusCodeerrormessage

我能够通过在此对象上设置.details来输出动臂错误的细节:

{
      method: 'PUT',
      path:'foo',
      handler: function (request, reply) {
        var err = Boom.badRequest('something', { stuff: 'and more' });
        err.output.payload.details = err.data;
        reply(err);
      }
}

这不是世界上最理想的东西,但可能是安全的默认值。

我有同样的问题,虽然我不能采取你采取的方法,但 Boom 常见问题解答中有以下内容:

问题 如何在回复中包含额外信息? output.payload 缺少数据,是什么?

答案 在响应有效负载中传回的值是有原因的 被锁定了。这主要是为了安全,并且不会泄漏任何 重要信息返回给客户。这意味着您将需要 付出更多的努力来包含有关您的额外信息 自定义错误。查看快乐中的"错误转换"部分 文档。

也:

我发现(奇怪的是),正如文档所示(但不是示例用法),将消息传递给badImplementation将被忽略,而将消息传递给notImplemented - 两者都是 5xx 错误。

文档:不良实施与未实现

传递额外的参数是通过数据对象完成的,但是,如代码中所述

/**
 * Custom error data with additional information specific to the error type
 */
data?: Data;

它只是特定错误类型的特定信息

如果您完全坚持添加额外的参数,我找到了解决方法

const err = Boom.badData('this is bad data message')
err.output.payload = { ...err.output.payload, attributes: { a: 'bb', c: 'ddd' } }
return err

这将产生以下有效负载:

{
  "statusCode": 422,
  "error": "Unprocessable Entity",
  "message": "this is bad data message",
  "attributes": {
    "a": "bb",
    "c": "ddd"
  }
}

您可以编写自己的函数来包装这段代码并使用它