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:
- UnauthorizedError
- TooManyRequestsError
- SizeLimitError
- ServiceUnavailableError
- PreconditionError
- PluginImplementationError
- PartialError
- NotFoundError
- InternalError
- GatewayTimeoutError
- ForbiddenError
- ExternalServiceError
- BadRequestError
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
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:
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:
throw app.errors.get('app', 'api', 'custom', 'Something bad happen');
Edit this page on Github(opens new window)