as you know the default error interface in Fastify looks like
{
"statusCode": 400,
"error": "Bad Request",
"message": "Missing property blah-blah"
}
I really would like to be able to throw back something like
{
"statusCode": 400,
"error": "Bad Request",
"message": "Missing property blah-blah",
"myCustomError": "yo yo I am custom"
}
I tried multiple (really a lot!) combinations of using the setErrorHandler and addHook("onError") and I cannot return any custom error.
No matter what I do, the custom errors I throw from inside my handlers are somehow converted to this default interface and can't see to find a way around it. I also tried using the onSend and onResponse hooks, too. Nothing I tried worked out. :(
Is it even possible to return custom errors in Fastify v3? If not possible in v3, what about Fastify v4? Can anybody be so good to provide a code design which enables custom errors in Fastify?
Whenever you return/throw an
Error, Fastify handles it with the default serializer that does not contain any additional properties.To do so, you need to list the fields you want as output:
This code works for fastify v3 and v4
Consider to read this article too