Skip to content

Throw custom Joi Errors #779

@eightyfive

Description

@eightyfive

Hi,

That would be nice if Joi could throw custom Joi Errors:
https://github.com/hapijs/joi/blob/master/lib/errors.js#L140

Something in the fashion of:

/**
 * Custom Joi Error
 */
function JoiError() {
  Error.apply(this, arguments);

  this.details = [];
  // ...
}
JoiError.prototype = Object.create(Error.prototype);
JoiError.prototype.annotate = function () { /* ... */ }


// And later on...
try {
  // Some logic throwing a new JoiError(/* ... */);
  // ...
} catch (err if err instanceof JoiError) {
  // ...
  // Use Joi error details...
} catch (err if err instanceof TypeError) {
  // ...
}

It would make easier catching/narrowing to Joi-related errors in try {} catch (err) {} blocks as illustrated above. I am using koa and that would come very handy. For now I am testing if the thrown err has a details property which is not exactly future-proof nor elegant...

Or may you have a better suggestion to cast Joi errors only?

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions