errors
errors copied to clipboard
Error doesn't inherit status code from Http400Error
var errors = require('errors');
errors.create({
name: 'ValidationError',
defaultMessage: 'Validation error',
defaultExplanation: 'Some properties are not valid',
defaultResponse: 'Resend the object with valid properties',
parent: errors.Http400Error
});
// Status property is 500 instead of 400.
console.log(new errors.ValidationError())
Is there a way to fix this?
@vjames19 as per https://github.com/bodenr/errors/blob/master/lib/errors.js#L321 the status is based on the exception instances errorCode which is passed into the instance factory as code. If this value is a valid HTTP status code its used, otherwise it's defaulted to 500. If you don't pass in a code on the factory call, a new code will be generated and used for your exception instances -- this new code starts at 601 and is incremented for each new prototype you create with errors.create().
If you want to explicitly set to 400 you can do something like this:
errors.create({
name: 'ValidationError',
defaultMessage: 'Validation error',
defaultExplanation: 'Some properties are not valid',
defaultResponse: 'Resend the object with valid properties',
code: 400,
parent: errors.Http400Error
});
which would give you:
{ explanation: 'Some properties are not valid',
response: 'Resend the object with valid properties',
code: 400,
status: 400,
name: 'ValidationError',
message: 'Validation error' }
I can see how by passing in the parent you would expect to inherit the status code if one exists, but today that does not happen. I'm willing to consider an "enhancement" for this if you think its warranted. However such a change would need to be backwards compatible with the current behavior -- for example accepting a new property in the options you pass into create to specify to use parent's code if it exists.
If you think such a change would be good feel free to submit a PR or let me know and I can try to code something up time permitting.
thanks
I think being able to inherit or set a status separately from the code would make sense... if you specify a "status" with the create, could that explicitly set a status separate from the generated "code" ?