hapi-pino icon indicating copy to clipboard operation
hapi-pino copied to clipboard

Logging non 5xx error details

Open ncjones opened this issue 5 years ago • 2 comments

Hapi-pino should log the error details for any uncaught error regardless of what status code the response is mapped to. For example, if a route handler throws Boom.forbidden('Some Reason') then the log for the response should include the error details just as it does when an unknown error is thrown such as throw Error('Some Reason').

The Hapi request event docs state that any uncaught error response will be emitted with "handler" and "error" tags along with the error so maybe this gap is due to a bug in Hapi. The Hapi response event for these non-5xx error responses does make the uncaught error available via the "response._error" property though so hapi-pino could implement a workaround.

I also posted this as a question in the general Hapi Slack channel but as yet have not had an answer.

ncjones avatar Jul 12 '20 04:07 ncjones

Would you like to send a Pull Request to address this issue? Remember to add unit tests.

mcollina avatar Jul 12 '20 07:07 mcollina

As temporary solution in my projects, I add my own 'response' event listener and log an additional line for the request if it responded with 4xx status code.

I log either the error at the response._error property or the response body if it is an object using response.source property:

server.events.on('response', function log4xxErrorDetails(request) {
  const { response } = request

  if (!response) {
    return
  }

  const { statusCode } = response

  const statusCodeIsWithinRange = statusCode >= 400 && statusCode < 500

  if (statusCodeIsWithinRange === false) {
    return
  }

  const details =
    typeof response._error === 'object'
      ? response._error
      : response.variety === 'plain' && typeof response.source === 'object'
      ? response.source
      : null

  if (details == null) {
    return
  }

  logger.info(
    { details, req: request, res: request.raw.res },
    'request responded with %d error -- %s',
    statusCode,
    details.message
  )
})

illarionvk avatar Aug 05 '20 14:08 illarionvk