Cross-posting the answer I gave on GitHub in https://github.com/strongloop/loopback-next/issues/1867#issuecomment-434247807
Building HTTP error responses is a tricky business. It's easy to get it wrong and open your application to attacks.
In LoopBack (both 3.x and 4.x), we use our strong-error-handler middleware to take care of this. See Handling Errors in our docs.
Here are the important security constraints to keep in mind:
In production mode, strong-error-handler
omits details from error responses to prevent leaking sensitive information:
- For 5xx errors, the output contains only the status code and the status name from the HTTP specification.
- For 4xx errors, the output contains the full error message (
error.message
) and the contents of the details
property (error.details
) that ValidationError
typically uses to provide machine-readable details about validation problems. It also includes error.code
to allow a machine-readable error code to be passed through which could be used, for example, for translation.
In debug mode, strong-error-handler
returns full error stack traces and internal details of any error objects to the client in the HTTP responses.
Now that I have warned you, LoopBack 4 makes it very easy to format the error messages your way. Just provide a custom implementation of the Sequence action reject
. See Customizing Sequence Actions in our docs, it explain how to create a custom send
action. The solution for reject
is pretty much the same, you just need a different signature for the action function.
export class CustomRejectProvider implements Provider<Reject> {
// ...
action({request, response}: HandlerContext, error: Error) {
// handle the error and send back the error response
// "response" is an Express Response object
}
}
Caveat: some errors thrown by LB4 have only code
set, these errors need a bit of pre-processing to decide what HTTP status code they should trigger. (For example, the error code ENTITY_NOT_FOUND
should be mapped to the status code 404
). The built-in reject
action does not yet expose this pre-processing for consumption by custom reject actions. It's an oversight on our side, l created a new issue https://github.com/strongloop/loopback-next/issues/1942 to keep track of that.