Fatal Exception: connection refused (Fuel.get)

I’m really new to Kotlin and I think it may be inexperience causing my problem, I’m hoping someone can help enlighten me - I have searched everywhere I can think of and have not been able to come up with a solution.

I have an android app that needs to connect to a remote server on startup. I have a very simple usage of Fuel to get the required data:

try {
    Fuel.get(url, params).responseString { request, response, result ->
        handleResults(result.get())
    }
}
catch (e:Exception) {
    handleError(e)
}

But when there is a connection problem such as the server being down, I get a fatal exception that isn’t handled by my catch block. This action happens when the app opens, so this is causing the app to fail completely, crashing immediately upon start. I just want to get past this so I can display an error for the user.

I have been reading about coroutines and async operations to try to find a way around this, but I haven’t found anything that works with the code I’m using. I guess that Fuel handles the async part internally, so I don’t really use any of that to make this connection. (I’m also not sure if I should wrap Fuel in an async - how nested can I get?)

Anyone have any suggestions how to catch the error?

An abbreviated stack trace for some context:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my.app PID: 19026
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
     Caused by: Connection refused
  com.github.kittinunf.fuel.core.FuelError$Companion.wrap(FuelError.kt:84)
    com.github.kittinunf.fuel.core.FuelError$Companion.wrap$default(FuelError.kt:83)
    com.github.kittinunf.fuel.core.requests.RequestTaskCallbacks.call(RequestTaskCallbacks.kt:30)
    com.github.kittinunf.fuel.core.requests.RequestTaskCallbacks.call(RequestTaskCallbacks.kt:20)
    java.util.concurrent.FutureTask.run(FutureTask.java:237)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    java.lang.Thread.run(Thread.java:761)
    Caused by: Connection refused
2 Likes

Hi
The issue you are having is regarding the way you handle exceptions.
If you change the catch from Exception to Throwable , then it should work.

Replace

catch (e: Exception)

With

catch (t: Throwable)
1 Like