How to throw custom validation errors back to client in REST response
In our loopback application, we are doing some custom validations via operation hooks and want to throw back the error (if validation fails) as response to REST API call with some valid status code. Currently we are doing something like : next(new Error('Error message goes here....')); But with this client calling the REST only recieves the 500: Internal server error in response and not the actual error, and corresponding loopback application shows 'Unhandled error for request....' How can we send custom error codes in these cases along with the custom error messages back to client making the REST calls?
Currently i have the following in middleware.json for error handling:
"final": { "loopback#urlNotFound": {} }, "final:after": { "strong-error-handler": {} }
Please suggest how can we fix this urgently.
we are facing same issue
@JyotiRani , @ghulamhussain , what's the loopback version? Also, to help us triaging the issue, please provide a sample repo? Thanks.
@dhmlau i don't have a sample repo as of now, but it can be easily reproduced by e.g. writing a before save operation hook for a model and validate on certain field and if validation fails instead of calling next(), call next(new Error('Field is invalid'); this way you should be able to reproduce the issue. i.e. API caller in this case doesn't get 'Field is invalid' message in response rather 'Internal server error' with 500 status code. We need a way to pass these custom error messages to caller as well as some custom code like 400 etc., how can we achieve this?
"loopback": "^2.22.0", "loopback-boot": "^2.6.5", "loopback-component-explorer": "^5.0.0", "loopback-component-storage": "^3.2.0", "loopback-connector-dashdb": "^1.0.18", "loopback-connector-rest": "^2.1.0", "mqlight": "^2.0.2017062000", "multer": "^1.3.0", "serve-favicon": "^2.0.1", "strong-error-handler": "^2.0.0"
@dhmlau i don't have a sample repo as of now, but it can be easily reproduced by e.g. writing a before save operation hook for a model and validate on certain field and if validation fails instead of calling next(), ...
@JyotiRani , if it's easy to reproduce, do you mind creating one? It would really help us to accelerate the triage process.
@ghulamhussain, if you have one, please send it our way!
Thanks a lot!
example_exception_handling.zip
Attaching the example App. Please extract the zip and install npm modules. Example allows name should be less than 5 chars long in post request, if name is >5 in length custom error is thrown:
Sample POST request http://localhost:3000/api/contacts {"name": "Bob test is here"}
this results into error, however what client gets in response is "Internal server error" not the custom error defined in the before save hook. Please help!
Please try the following code for common/models/contact.js.
"use strict";
module.exports = function(Contacts) {
Contacts.observe("before save", function(ctx, next) {
console.log(
"> before save triggered:",
ctx.Model.modelName,
ctx.instance || ctx.data
);
var data = ctx.instance || ctx.data;
console.log(data);
if (data.name.length < 5) {
next();
} else {
//performValidations(ctx, next);
var err = new Error("Name should contain max 5 chars");
err.statusCode = 400;
return next(err);
}
});
};
var err = new Error("Name should contain max 5 chars");
err.statusCode = 400;
return next(err);
FWIW, this can be simplified using http-errors module.
// at the top
const HttpErrors = require('http-errors');
// in the hook
return next(new HttpErrors.BadRequest('Name should contain max 5 chars'));
The important part is that strong-error-handler (and many other error-handling middleware) looks at statusCode property when deciding what HTTP status code to return. It does not matter how this property is set, whether manually via err.statusCode = 400 or by using a custom class like HttpErrors.BadRequest.
Thanks...its working as expected now!
Loopback error object requires name, status and message properties
const error = new Error("something wrong"); // message as param
error.name = "ERROR";
error.status = 400;
return next(error);
https://loopback.io/doc/en/lb3/Error-object.html