Core
Guides v2.x
2

Customize API Errors #

It is possible to customize the errors that we want to return in case of failure of an API request.

Kuzzle offers a set of standard errors corresponding to specific situations with customizable messages (e.g. NotFoundError,ForbiddenError, etc.)

Standard Errors #

Kuzzle exposes standard API errors classes.

The following constructors are available directly in the kuzzle package:

If a non-standard error is thrown, Kuzzle will instead return a standard PluginImplementationError error, embedding the thrown error.

Example: Throw a PreconditionError when an action parameter is missing

Copied to clipboard!
import { Backend, PreconditionError } from 'kuzzle';

app.controller.register('greeting', {
  actions: {
    sayHello: {
      handler: async request => {
        if (request.input.args.name === undefined) {
          throw new PreconditionError('Missing "name" argument.');
        }

        return `Hello, ${request.input.args.name}`;
      }
    }
  }
});

Use preconfigured errors #

Each standard error also have a standard Error Code.

You can register custom standard errors:

Copied to clipboard!
app.errors.register('app', 'api', 'custom', {
  class: 'BadRequestError',
  description: 'This is a custom error from API subdomain',
  message: 'Custom %s error',
});

And then retrieve them to throw standard errors:

Copied to clipboard!
throw app.errors.get('app', 'api', 'custom', 'Something bad happen');