Errors

GitHub stars
@feathersjs/errors"">npm version
Changelog

  1. $ npm install @feathersjs/errors --save

The @feathersjs/errors module contains a set of standard error classes used by all other Feathers modules as well as an Express error handler to format those - and other - errors and setting the correct HTTP status codes for REST calls.

Feathers errors

The following error types, all of which are instances of FeathersError are available:

ProTip: All of the Feathers plugins will automatically emit the appropriate Feathers errors for you. For example, most of the database adapters will already send Conflict or Unprocessable errors with the validation errors from the ORM.

  • 400: BadRequest
  • 401: NotAuthenticated
  • 402: PaymentError
  • 403: Forbidden
  • 404: NotFound
  • 405: MethodNotAllowed
  • 406: NotAcceptable
  • 408: Timeout
  • 409: Conflict
  • 411: LengthRequired
  • 422: Unprocessable
  • 429: TooManyRequests
  • 500: GeneralError
  • 501: NotImplemented
  • 502: BadGateway
  • 503: Unavailable

Feathers errors contain the following fields:

  • name - The error name (ie. “BadRequest”, “ValidationError”, etc.)
  • message - The error message string
  • code - The HTTP status code
  • className - A CSS class name that can be handy for styling errors based on the error type. (ie. “bad-request” , etc.)
  • data - An object containing anything you passed to a Feathers error except for the errors object.
  • errors - An object containing whatever was passed to a Feathers error inside errors. This is typically validation errors or if you want to group multiple errors together.

ProTip: To convert a Feathers error back to an object call error.toJSON(). A normal console.log of a JavaScript Error object will not automatically show those additional properties described above (even though they can be accessed directly).

Custom errors

You can create custom errors by extending from the FeathersError class and calling its constructor with (msg, name, code, className, data):

  • message - The error message
  • name - The error name (e.g. my-errror)
  • code - An HTTP error code
  • className - The full name of the error class
  • data - Additional data to inclue in the error
  1. const { FeathersError } = require('@feathersjs/errors');
  2. class UnsupportedMediaType extends FeathersError {
  3. constructor(message, data) {
  4. super(message, 'unsupported-media-type', 415, 'UnsupportedMediaType', data);
  5. }
  6. }
  7. const error = new UnsupportedMediaType('Not supported');
  8. console.log(error.toJSON());

Examples

Here are a few ways that you can use them:

  1. const errors = require('@feathersjs/errors');
  2. // If you were to create an error yourself.
  3. const notFound = new errors.NotFound('User does not exist');
  4. // You can wrap existing errors
  5. const existing = new errors.GeneralError(new Error('I exist'));
  6. // You can also pass additional data
  7. const data = new errors.BadRequest('Invalid email', {
  8. email: 'sergey@google.com'
  9. });
  10. // You can also pass additional data without a message
  11. const dataWithoutMessage = new errors.BadRequest({
  12. email: 'sergey@google.com'
  13. });
  14. // If you need to pass multiple errors
  15. const validationErrors = new errors.BadRequest('Invalid Parameters', {
  16. errors: { email: 'Email already taken' }
  17. });
  18. // You can also omit the error message and we'll put in a default one for you
  19. const validationErrors = new errors.BadRequest({
  20. errors: {
  21. email: 'Invalid Email'
  22. }
  23. });

Server Side Errors

Promises swallow errors if you forget to add a catch() statement. Therefore, you should make sure that you always call .catch() on your promises. To catch uncaught errors at a global level you can add the code below to your top-most file.

  1. process.on('unhandledRejection', (reason, p) => {
  2. console.log('Unhandled Rejection at: Promise ', p, ' reason: ', reason);
  3. });

Error Handling

It is important to make sure that errors get cleaned up before they go back to the client. Express error handling middlware works only for REST calls. If you want to make sure that ws errors are handled as well, you need to use App Hooks. App Error Hooks get called on an error to every service call regardless of transport.

Here is an example error handler you can add to app.hooks errors.

  1. const errors = require("@feathersjs/errors");
  2. const errorHandler = ctx => {
  3. if (ctx.error) {
  4. const error = ctx.error;
  5. if (!error.code) {
  6. const newError = new errors.GeneralError("server error");
  7. ctx.error = newError;
  8. return ctx;
  9. }
  10. if (error.code === 404 || process.env.NODE_ENV === "production") {
  11. error.stack = null;
  12. }
  13. return ctx;
  14. }
  15. };

then add it to the error.all hook

  1. module.exports = {
  2. //...
  3. error: {
  4. all: [errorHandler],
  5. find: [],
  6. get: [],
  7. create: [],
  8. update: [],
  9. patch: [],
  10. remove: []
  11. }
  12. };