数据:hapi.js preResponse 中的 null,如果抛出错误

data: null in hapi.js preResponse, if Error was thrown

我在模式代码的某处抛出这样的错误:

throw new Error({
    name: 'notFound',
    message: 'Book not found'
});

我有一个 onPreResponse 服务器扩展:

server.ext('onPreResponse', async ({ response }, h) => {
    if (isErrorResponse(response)) {
        // So, here the "data" property is null and I can not access name and message
        console.dir(response);
    }
    return h.continue;
});

因为数据为空,所以我无法访问我的名字和消息。但是,如果我抛出普通对象,我将拥有这两个属性。虽然那将是一个 hapi 错误 Cannot throw non-error object

如果不太了解 onPreResponse 捕获错误的意图,这里可能有一些事情可以考虑

https://hapijs.com/api#-requestresponse

The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, return a new response value. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).

所以数据为空是预期的行为,所以我知道您想以某种方式丰富错误。 Hapi 中抛出的错误会自动转换为 Boom object now you are trying to throw and Error that is not right constructed, see Error constructor docs 第一个参数是错误消息,而不是自定义对象。相反,您可以使用构造函数允许您在其中放置自定义数据的 Boom 错误,例如

throw new Boom('Book not found', { statusCode: 404, decorate: { custom: 'custom' } });

所以如果你扔那个你应该看到以下属性

{
  "data": null,
  "isBoom": true,
  "isServer": false,
  "output": {
    "statusCode": 404,
    "payload": {
      "statusCode": 404,
      "error": "Not Found",
      "message": "Book not found"
    },
    "headers": {}
  },
  "custom": "custom"
}

您现在可以添加一些日志记录来检查响应是否为错误 ( if(response.isBoom) ) 并读取错误传递的自定义信息。无论如何,我确实认为最好不要在 onPreResponse 扩展中使用这种类型的逻辑,我会尝试使用常见的错误处理冒泡错误从更深层到请求处理程序并从那里返回适当的 Boom 错误。