Skip to content

Instantly share code, notes, and snippets.

@ejmudrak
Created September 19, 2022 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejmudrak/c628fa0e04317914b50e109cbf52c99b to your computer and use it in GitHub Desktop.
Save ejmudrak/c628fa0e04317914b50e109cbf52c99b to your computer and use it in GitHub Desktop.
Feathers Schema Validation Error Helpers
import { FeathersError } from '@feathersjs/errors';
import { DefinedError } from 'ajv';
import { HookContext } from '@feathersjs/feathers';
class ValidationError extends FeathersError {
constructor(message: string, data: DefinedError[]) {
super(message, 'Validation Failed', 400, '', data);
}
}
export const errorHandler = (context: HookContext) => {
// Handles Feathers schema validation errors
if (context.error.message === 'validation failed') {
const error = context.error;
const validationErrors: DefinedError[] = error.data;
const {
hook: { path, method, type },
} = error;
const data: DefinedError[] = validationErrors.map((e) => {
return { ...e, service: path, method, hookType: type };
});
let message = '';
if (process.env.NODE_ENV === 'testing') {
// Prints out full error
message += `\nIn service: ${error.hook.path}, \n`;
message += `In method: ${error.hook.method}, \n`;
message += `In hook: ${error.hook.type}, \n`;
message += `Error: ${JSON.stringify(validationErrors)}`;
} else {
const paramsString = JSON.stringify(validationErrors[0].params)
.replace('{', '')
.replace('}', '');
// Prints out more human-readable error
message += `${validationErrors[0].message} - ${paramsString}`;
}
const newError = new ValidationError(message, data);
context.error = newError;
return context;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment