h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Custom error status for readValidatedBody, readValidatedQuery, etc

Open cosbgn opened this issue 10 months ago • 3 comments

Describe the feature

I love readValidatedBody but 400 as status error is too generic, I use it for all sort of errors and I would like to have the ability to set a better error code.

Ideally it would simply be: readValidatedBody(event, schema.parse, 422)

it can be 400 as default so it wouldn't be a breaking change, even tough I would personally prefer 422

Additional information

  • [ ] Would you be willing to help implement this feature?

cosbgn avatar Feb 24 '25 13:02 cosbgn

PR welcome. Perhaps we could keep it more generic like readValidatedBody(event, schema, { failStatus: 422 }). /cc @sandros94 what do you think?

pi0 avatar Jun 04 '25 22:06 pi0

PR welcome. Perhaps we could keep it more generic like readValidatedBody(event, schema, { failStatus: 422 }). /cc @sandros94 what do you think?

Yes, an api that I usually add into my own projects (focused on valibot tho) is something like:

function createValidationError<DataT = unknown>(
  error: any,
  overrides?: Partial<H3Error<DataT>> & {
    status?: number
    statusText?: string
  },
) {
  return createError({
    status: 400,
    statusMessage: 'Validation failed',
    ...overrides,
    data: error,
    message: v.isValiError(error)
      ? v.summarize(error.issues)
      : error.message
        ? error.message
        : undefined,
  })
}

Used indeed as readValidatedBody(event, schema, { statusMessage: 'My Message' })

But rethinking about this it would be nice to access the ReadonlyArray<Issue> that comes from Standard-Schema's issues via a callback or similar, WDYT?

sandros94 avatar Jun 04 '25 22:06 sandros94

I did experiment with this last weekend, I do plan to work on what I think is a nice and flexible implementation in the upcoming days/weeks

sandros94 avatar Jul 02 '25 12:07 sandros94