sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.77k stars 152 forks source link

Include `Value.Errors` array on thrown errors #776

Closed aleclarson closed 6 months ago

aleclarson commented 6 months ago

When an error is thrown by Value.Encode or Value.Decode, the TypeBoxError should have the validation issues attached to it.

aleclarson commented 6 months ago

Oh, what do ya know... it is already! Just use error.error to access it.

aleclarson commented 6 months ago

I guess the only issue is that it's not exposed to TypeScript anywhere.

Here's a little hack I'm using (warning: potentially fragile):

import {
  TransformDecodeCheckError,
  TransformEncodeCheckError,
} from '@sinclair/typebox/build/require/value'

export const isTypeError = (
  error: any
): error is TransformEncodeCheckError | TransformDecodeCheckError =>
  error.constructor.name.endsWith('CheckError')

// Example
if (isTypeError(e)) {
  console.log(e.error) // ✔️
}