improve handling of non-object errors thrown in endpoint handlers
See original GitHub issueoh boy, i just spent the last couple hours running in circles trying to figure this one out. my API endpoint was returning {"status":"success"}
with no data, which was then causing errors when my generated client was assuming "status":"success"
means data
should be present
the culprit is this:
- the error is only passed to the result handler if it’s
instanceof Error
- https://github.com/RobinTail/express-zod-api/blob/721a41e2f762a9f0a524fc111549c461d9057462/src/endpoint.ts#L333-L335 - if there’s no error passed to the result handler, it returns a 200 and a success status regardless of whether there’s any real data or not - https://github.com/RobinTail/express-zod-api/blob/721a41e2f762a9f0a524fc111549c461d9057462/src/result-handler.ts#L83-L89
- turns out that running
prettier
programmatically throws astring
😅 - this was in my code
I was about to open a PR up but I’m actually not really sure how you want to handle this since this will be a breaking change, albeit a needed one IMO (probably before the v8 release?). the two obvious choices seem to be:
- widening the typings on the
ResultHandler
so you can pass in any kind of error (thus passing the onus to the default handler or the downstream consumer to handle more error cases) - just stringify any non-object error and create an Error object out of it
the latter seems way easier and with less breaking changes, whereas the former will certainly break any custom result handler implementations. but if you’re gonna make a breaking change anyway, I think the former is the way to go because if you just coerce everything into a string then it gives downstream consumers no way to implement custom error handling based on the type of the error
so my suggestion is to change the error type in the ResultHandler
to unknown
, then check if it’s !== undefined
(or != null
to handle both undefined & null?) rather than just checking if it’s falsey like you currently do. but not sure if you’ve got some other thoughts on how to better handle this?
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:5 (5 by maintainers)
Top GitHub Comments
🚀 The fix released in version 7.9.2. Thank you so much @rayzr522
I think I’m going to go with the second approach
There is no need to widen the signature of
ResultHandler
, we just need to handle morethrow
ing cases in endpoints and middlewares.