I am using the ajv errors plugin for fastify to throw schema errors for required properties however every error is prefixed with 'body' then my error message. Is there any way to remove the schema prefix from errors?
example:
body: {
type: 'object',
properties: {
title: {
type: 'string',
description: "The title of the thing",
},
required: ['title'],
errorMessage: {
required: {
title: 'BEEP BOOP TITLE NEEDED!',
},
},
},
my fastify config:
const app = fastify({
ajv: {
customOptions: {
allErrors: true,
},
plugins: [(ajv) => AjvErrors(ajv, { singleError: false, keepErrors: false })],
},
});
Expected error for missing title in a request: 'BEEP BOOP TITLE NEEDED!'
Actual: 'body BEEP BOOP TITLE NEEDED!''
fastify: "4.1.0"
ajv-errors: "3.0.0"
CodePudding user response:
What you can do is a simple trick with fastify ;)
fastify.setErrorHandler(function (error, request, reply) {
// Log error
this.log.error(error);
const err = error;
if (error?.validation?.length) {
err.message = error.validation[0].message;
}
// Send error response
return reply.status(error.statusCode || 400).send(err);
});
CodePudding user response:
There is the schemaErrorFormatter
option
const fastify = Fastify({
schemaErrorFormatter: (errors, dataVar) => {
// errors = ajv errors
// dataVar = `body` string
return new Error(myErrorMessage)
}
})