throw errors in createServerFn and catch it
hey, what is the correct way to throw errors in createServerFn()? im trying this -> make a call to my backend, which returns a 400 error with a json { "error": "msg" }. inside createServerFn i check res.ok, if not, throw an Error with backend message. but, when i create a mutation with react-query, and want to manage onError, error always is 500 and default error message
5 Replies
adverse-sapphire•10mo ago
foreign-sapphire•10mo ago
for now i do this
throw json(body, { status: 400 })
this kind of works, but it is neither documented nor ideal. The request is aborted, and the status is indeed 400; but when catching the error, you must JSON parse the message property to get the body.
you can do that, or work with monadic types to bubble up the error as json up to the point where you return your response
this honestly the only big pain point i have with TS Start. There is no clean way to respond with errors by aborting the request.
Although it could be argued that aborting by throwing is not clean by itself; which would be acceptable if you could abort in a middleware without throwing, but you just can’tflat-fuchsiaOP•10mo ago
thanks @cusx @notKamui, this (throw json) solves my problem temporarily. but yes, I think the documentation should be clearer about this, i have not found in the examples section of the documentation any example of mutation with createServerFn
foreign-sapphire•10mo ago
i posted an entry in the discussions tab on github, but i still don’t have any answer on it
foreign-sapphire•10mo ago
GitHub
[Start]: Throwing errors with a status code · TanStack router · Dis...
Would it be possible to throw errors in server functions / middlewares along with a custom status code instead of systematically respond with a 500 code. For clarity and documentation, always retur...