Create consistent error objects around the codebase
npm install @directus/errorsUtility functions to help creating and checking against Directus errors.
```
pnpm add @directus/errors
``
createError(code: string, message: string | (T) => string, status = 500): DirectusErrorConstructor
`ts
import { createError } from '@directus/errors';
const ForbiddenError = createError('FORBIDDEN', "You don't have permissions to see this.", 403);
throw new ForbiddenError();
`
You can configure additional extensions for the error class which should be communicated to the end user:
`ts
import { createError } from '@directus/errors';
interface ForbiddenErrorExtensions {
collection: string;
field: string;
}
const ForbiddenError = createError
'FORBIDDEN',
"You don't have permissions to see this.",
403,
);
throw new ForbiddenError({
collection: 'articles',
field: 'title',
});
`
You can then also use those extensions to generate out the error message:
`ts
import { createError } from '@directus/errors';
interface ForbiddenErrorExtensions {
collection: string;
field: string;
}
const messageConstructor = (extensions: ForbiddenErrorExtensions) =>
You don't have permissions to see "${extensions.field}" in "${extensions.collection}".;
const ForbiddenError = createError
throw new ForbiddenError({
collection: 'articles',
field: 'title',
});
`
`ts
import { isDirectusError, createError } from '@directus/errors';
const ForbiddenError = createError('FORBIDDEN', "You don't have permissions to see this.", 403);
isDirectusError(new ForbiddenError()); // true
isDirectusError(new Error()); // false
``