I am using strongloop 4 (lb4). I am facing one issue that in error object I need to one more custom parameter in the error object.
I want it on the global level. On every error, I want to add that custom parameter in every error message.
In loopback4 global error handling is done by src/sequence.ts.
Suppose the error message object is.
{
"error": {
"statusCode": 400,
"name": "xyz",
"message": "firstName is required"
}
}
I want error object output like.
{
"error": {
"customParam" : "customParam",
"statusCode": 400,
"name": "xyz",
"message": "firstName is required"
}
}
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:
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 customsendaction. The solution forrejectis pretty much the same, you just need a different signature for the action function.Caveat: some errors thrown by LB4 have only
codeset, these errors need a bit of pre-processing to decide what HTTP status code they should trigger. (For example, the error codeENTITY_NOT_FOUNDshould be mapped to the status code404). The built-inrejectaction 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.