Closed chris-deep closed 8 months ago
Which version are you using? As of 4.2.x
, withContent
should not be throwing... it'll waterfall through attempts against json
-> formData
-> text
, with catches at each stage. There should be nothing you can do to accidentally throw during one of those.
As of 4.2.2
(released just now), the entire thing with correctly return undefined if no request.body exists (<4.2.1
returned empty string incorrectly, but still didn't throw).
Now, theoretically if you wanted to stay on the older version, you could do one of the following:
handle/fetch
. This will return a well formed error response, but not one specific to your case:
export default {
fetch: (req, ...args) =>
router
.fetch(req, ...args)
.then(json) // example of downstream formatter
.catch(error) // example of downstream catches, returning a 500
}
Add your own middleware that catches :)
const withContentNoThrow = async (request) => {
request.content = await request.json().catch() // won't throw
}
const withContentCustomThrow = async (request) => {
try {
request.content = await request.json()
} catch(err) {
return error(400, 'Could not parse request.json as JSON.')
}
}
Hope that helps!
Ahhhh ok excellent. I'm on v4.0.27. I'll upgrade and test it. Right those samples make sense too! Thanks, good stuff 👍
IttyRouter is freakin cool.... really like it
Confirming I no longer get unhandled exceptions with IR... thanks!
Confirming I no longer get unhandled exceptions with IR... thanks!
Awesome, glad to hear it! Btw, in general, I'm pretty terrible about noticing issues in time (got lucky tonight) - I'd def recommend joining our discord channel where the wonderful community folks are WAY faster to answer questions!
Ahhhh ok excellent. I'm on v4.0.27. I'll upgrade and test it. Right those samples make sense too! Thanks, good stuff 👍
IttyRouter is freakin cool.... really like it
I love to hear that!
Brace yourself for some big changes (in a good way)! We have v4.3x
pending release, which will drastically streamline the boilerplate for Bun/Cloudflare Workers (the Router lineup increases a bit), plus an entire docs site revamp that i'm working on this weekend to match the release.
Describe the Issue
If I send a malformed request to my API using withContent, it throws an unhandled exception. How do I wrap withContent with a try/catch?
Example Router Code
N/A - send a malformed request POST to any of your withContent handlers
Request Details
url - https://api.x.co/auth/login body - "sample_invalid_input" (should be json for example)
Expected Behavior
A caught exception
Actual Behavior
An uncaught exception
Environment (please complete the following information):
Cloudflare Workers