Catching net::ERR_CONNECTION_REFUSED, with authClient?
Using authClient fort signIn:
I am hypothetically testing if my api is down.
Why doesn't
better-auth
return better errors for this?
I wrapped in try
catch
and no error seems to be thrown. Only see net::ERR_CONNECTION_REFUSED
in console
How can I reliably check for extraneous errors like network?
1. data returns null
2. error returns
Reliable way to check if data
null then or when error.status === 0
? Something is wrong error?
I think authClient should at least throw an error so a catch block can take it.17 Replies
you can use
onError : (err) => {}
Do I need to handle
error
returned at the top not?probably its broken, you can use onError
I don’t follow.
What is the difference between returned error from function and onError
its same
It has try catch block inside and it handles the error you want to handle. This is the boilerplate I use when I want to return error as part of function:
I blame javascript not
better-auth
for thissounds like a bad idea in my opinion, i had a 401 unauthorized error that got classified as internal server error

now lets try shutting the API backend down completely and see what error it throws

same thing again
- i am not an expert at this stuff by any means but i have a far better method i believe
feel free to correct or improve
- catches all the errors perfectly as far as i tested
you need to install @better-fetch/fetch separately it seems in order to import BetterFetchError, unbelievable that they have not exported this error from better-auth

when there is a network error this one clearly indicates it

also highlights the unauthorized error clearly
but i gotta admit, status === 0 is absolutely the stupidest check i've had to do in a long freaking time
Yes I don't really need to distinguish errors in my case other that the validation ones (which have descriptive messages) because I don't need it...
You can do the check on
ctx.status
in the onError(ctx)
too and I believe it would work.
This looks better, I think I'll use that too as a good practice, thanks!so apart from doing status.code === 0 for a network error check, is there really no better way?
- Final update, i refactored a lot of stuff, this is the best i have come up with in terms of error handling
- it distinguishes network errors from better auth errors from better fetch errors big time
- I really wish better-auth would document how to do all this stuff yourself, cant find a single mention of how to separate errors, what are the types of errors to expect from the client, no word, nada
- also it is absolutely lame that i hvae to install @better-fetch/fetch just to import betterFetchError that better-auth throws every second, someone really needs to look into this one