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

Return ZodError on parse error #2

Open
PedroHase opened this issue Mar 18, 2023 · 1 comment
Open

Return ZodError on parse error #2

PedroHase opened this issue Mar 18, 2023 · 1 comment

Comments

@PedroHase
Copy link

PedroHase commented Mar 18, 2023

Hey,

I just noticed that when parsing the incoming request fails, a plain 500 error will be returned, but not the ZodError.

In order for consumers to understand what wen wrong with the request, I suggest to return the ZodError in the response body. I also would probably choose a different error code, e.g. 400, to let the consumer know that they did something wrong.

Here's how I solved it for myself:

// ... inside the try catch
} catch (error) {
      throw createError( // use @middy/utils instead of http-errors
        400, // return 400 error code instead of 500
        JSON.stringify({ // return the ZodError for the consumer so that they can understand what went wrong
          missingParameters: JSON.parse((error as any).message), // respond with error.message to return ZodError
        }),
        // in case other errors occur, add to error stack
        {
          cause: (error as any).message,
        }
      );
    }
// ...

Please note that I use @middy/http-error-handler in my setup which is why I stringify the response body.

Maybe an option could be added to specify the error code and whether the ZodError should be returned?

@revmischa
Copy link

revmischa commented Jan 4, 2024

I also am using @middy/http-error-handler and seem to get a 500 error when the validation fails
I'm working around it with something like this: https://gist.github.com/revmischa/3859f2b2ead79fae8b2b15a97b398378

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants