What is the best way to handle the error?
What I want is to get the error from server to client using rpc + react query
1. Using
trycatch
2. Returning c.json({ message: 'Invalid password' }, 401)
3. Throwing HTTPException(401, { message: 'Invalid password' })
16 Replies
I’m not very familiar with react query but I can try my best
Is the error your trying to get coming tonight the catch above?
I want to know how to handle errors inside the Hono server, so I can get the error within the React Query. What I used to handle the error is this:
return c.json({ message: 'Invalid password' }, { status: 401 })
on the Hono server. The problem is the 'onError' option of React Query doesn't catch it, so I used try-catch to pass the error to 'onError'. Normally, when fetching using the standard Fetch API and there's an error, React Query automatically passes it to 'onError'. But when using RPC, it doesn't pass to 'onError', so I'm not sure if the way I handled the error in my API route is correct. It still returns the error message as data, so I used try-catch."Fetch should only reject if the promise get rejected like a cors error. If there is body content even non non-200 status it will still pass
You need to check the status code or
response.ok
. You may be thinking of Axios which does throw errors for non-200 statuseshere's my hono server, I don't know what to choose to handle the error
but when I use
throw new HTTPException
it's not rejecting also, is it the same of return c.json({ message: 'Invalid password' }, { status: 401})
?It's not rejecting on the server?
this works for me, I thought
trycatch
is the same of !res.ok
return Promise.reject(data)
to pass the error
to onError
No it will only fire if catch did not receive a response with fetch
I mean if the body don't have a content it will consider as reject? so I tried to use
throw new HTTPException
to reject the promise unlike return c.json({message}, {status: 401})
this has a content even it's error
that's why I can't get the error from my server because I use trycatch
because the error is returning as a data
No sorry I mean like no body content was received so like the server did not respond or it was blocked by cors
Correct it still returns as data
In libraries like Axios it will reject if there is another else but 2xx
I got used to Axios where all errors are caught in try-catch.
It's happened to me as well, I used to only use Axios
that's why I thought also in fetch api standard is also can catch the error using trycatch
@igmtink will you close the discussion on GitHub as well to clear it up
Did you manage to fix the matter? @igmtink I'm getting the error too when using RPC + React Query