Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeBox errors are stringified instead of returning object #768

Open
ayZagen opened this issue Aug 5, 2024 · 0 comments
Open

TypeBox errors are stringified instead of returning object #768

ayZagen opened this issue Aug 5, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@ayZagen
Copy link

ayZagen commented Aug 5, 2024

What version of Elysia is running?

1.1.5

In the ValidationError constructor the typebox error result is stringified Line Reference.

I am already using SetErrorFunction provided by TypeBox and using my own messages.
Inside onError handler I cannot access the error object without parsing the error message. This applies an unnecessary overhead to application (additional parsing) as it is already an object.

Instead of stringifying the error object properties should be assigned to ValidationError instance. This will improve usability of ValidationError and there would be a slight increase in app throughput.

Example:

import {DefaultErrorFunction, SetErrorFunction, ValueErrorType} from '@sinclair/typebox/errors'
import {Elysia, t} from 'elysia'

SetErrorFunction((err) => {
  switch (err.errorType) {
    case ValueErrorType.ObjectRequiredProperty:
      return `object must contain required property "${err.path.replace('/', '')}"`
    case ValueErrorType.String:
      return 'the value must be a string'
    default:
      return DefaultErrorFunction(err)
  }
})
new Elysia()
  .post('/validate', ({body}) => body, {
    body: t.Object({
      name: t.String(),
      age: t.Number()
    }),
    error({code, error}) {
      switch (code) {
        case 'VALIDATION':
          return error.message
      }
    }
  })
  .listen(3000)

With the above code post an http request with an empty json to /validate endpoint. Because of missing property name it will return the following as a response

{
  "type": "validation",
  "on": "body",
  "summary": "Property 'name' is missing",
  "property": "/name",
  "message": "object must contain required property name",
  "expected": {
    "name": "",
    "age": 0
  },
  "found": {},
  "errors": [
// redacted for simplicity
   ]
}

However I only need "object must contain required property name" message, so I have to parse the error.message and return it.

EDIT: I have found that, we could use error.all[ 0 ].message, but still the stringification is unnecessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant