hapi-pino
hapi-pino copied to clipboard
Logging non 5xx error details
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.
Would you like to send a Pull Request to address this issue? Remember to add unit tests.
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
)
})