I'm using Loopback v3.x, and strong-error-handler for handling my project errors. The error response was fine in the development mode but when in production mode, it throws a different error back to the client.
I realised that it was the "debug": false"
that makes it throw an { error: { statusCode: 500, message: 'Internal Server Error' } }
(based from the Loopback documentation about strong-error-handler)
But I wanted to show my error in the production when I throw new Error('Error Messages')
with "debug": false
(to keep the sensitive data such as file paths, URLs, and stack traces out from exposure)
Below are my config files:
config.json
{
...
"remoting": {
"rest": {
"normalizeHttpPath": false,
"xml": false,
"handleErrors": false
}
}
}
middleware.development.json
{
"final:after": {
"strong-error-handler": {
"params": {
"debug": true,
"log": true,
"safeFields": [
"code"
]
}
}
}
}
middleware.json
{
"final:after": {
"strong-error-handler": {
"params": {
"debug": false,
"log": true,
"safeFields": [
"code"
]
}
}
}
}
I wanted the response to show the Error that I have thrown, like below:
I have went to strongloop-error-handler GitHub library but couldn't find any documentation about throwing the original error. Is it possible to do so?
So I went digging around the strong-error-handler library and found out that it is technically possible to do so if we set a statusCode
into the error manually, and has to be within 400 - 499.
in
buildResponseData()
function:
if (data.statusCode >= 400 && data.statusCode <= 499) {
fillBadRequestError(data, err);
} else {
fillInternalError(data, err);
}
https://github.com/strongloop/strong-error-handler/blob/master/lib/data-builder.js#L37
and the fillBadRequestError() will return the original error
function fillBadRequestError(data, err) {
data.name = err.name;
data.message = err.message;
data.code = err.code;
data.details = err.details;
}
https://github.com/strongloop/strong-error-handler/blob/master/lib/data-builder.js#L69
So, before throwing the error, we can set:
const error = new Error();
error.name = 'Custom Error';
error.message = 'Error Message';
error.statusCode = 404;
throw error;
Then it will return the error even with "debug": false
mode