fastify / fastify-response-validation

A simple plugin that enables response validation for Fastify.
MIT License
51 stars 14 forks source link

Identify response body validation error on setErrorHandler hook #121

Open JacopoPatroclo opened 3 days ago

JacopoPatroclo commented 3 days ago

Prerequisites

🚀 Feature Proposal

It would be helpful to have a way to identify errors emitted by this plugin in the context of the .setErrorHandler hook. The purpose of this feature is to clearly differentiate between validation errors triggered by input validation and those from output validation.

Motivation

The issue we’re facing is that we have no stable way of knowing whether the error was caused by input validation (where a 400 response would be appropriate) or output validation (where a 500 might be more suitable, as per the default behavior of this plugin). To clarify, the problem isn’t just about emitting the correct error code, but also performing additional logic. We need a reliable way to distinguish whether the validation error was triggered by this plugin or by standard input validation.

During our tests, we identified one way to check for the error, but as shown here, it's not a reliable implementation. It can easily break for various reasons.

if (error.validation && error.statusCode === 400) {
 // Handle Fastify's route input schema validation errors
}

if (error.validation && error.statusCode === undefined) {
 // Handle @fastify/response-validation's errors
}

Example

Maybe something like this could be useful

import { isResponseValidationError } from '@fastify/response-validation'

fastify.setErrorHandler(function (error, request, reply) {
    if (isResponseValidationError(error)) {
          // custom log and metrics
          reply.status(500).send(payload)
          return
    }
    // ... other stuff
})

If there are other solutions to this, I'm happy to use them.

JacopoPatroclo commented 3 days ago

If this is a valid proposal I can gladly open a PR implementing it.