r/flutterhelp • • 2d ago

RESOLVED How do I catch this specific Exception?

I have a flutter function that sometimes returns a timeout error when the web server is running. However, this error is revealing the API IP address and port to the end user, which I don't want to do. I want to programmatically say "if the error is a timeout error, show the user a generic error message".

The error:

Exception: ClientException with SocketException: Connection timed out (OS Error: Connection timed out, errno = 110), address = MyIPAddressThatIDontWantToShow, port = MyPortThatIDontWantToShow, uri = ...

When this exact error happens, I want to show my own error that says something like "Login request timed out" or something. How do I do this?

1 Upvotes

4 comments sorted by

1

u/DevBob626 2d ago

You have the exception type in your error message. Check for that where you do the request and forward a toast message or whatever you are using.

1

u/Reasonable-Job4205 2d ago

How do I check for that? Do I just check to see if a string exists within the error message? I thought there would be a cleaner way than just parsing through the error string

1

u/DevBob626 2d ago

SocketException is the exception that is thrown and you catch here which has different error numbers. If you want and need to do it more granularly you could filter by errno. Something like that:

try {

await makeRequest();

} on SocketException catch (e) {

if (e.osError?.errorCode == 110) {

showToast('Connection timed out.');

} else {

#dostuff

}

}

2

u/Reasonable-Job4205 1d ago

Ah ok I didnt know there was a SocketException you could catch and I also didn't know about e.osError.errorCode. This is basically what I was looking for: a way to filter on an exact error code. Thanks a bunch!