Hapi does not return data attribute from Boom erro

2019-06-18 05:53发布

问题:

When replying with a Boom error from my Hapi route...

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

... I get the following response:

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

It's missing the data object which provides the details of the error! What's the deal?

回答1:

On the Hapi documentation it references the output.payload property on the boom object, set by default to include statusCode, error and message.

I was able to output the details from the boom error by setting .details on this object:

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

Not the most ideal thing in the world, but probably a safe default.



回答2:

I had the same question, and although I can't take the approach you've taken, there is the following in the Boom FAQ:

Question How do I include extra information in my responses? output.payload is missing data, what gives?

Answer There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the "Error transformation" section in the hapi documentation.

Also:

I found that (strangely), as the docs indicate (but not the example usage), passing a message to badImplementation is ignored, whereas passing a message to notImplemented - both are 5xx errors.

Docs for: badImplementation vs notImplemented