无法捕获从其他函数引发的异常

问题描述 投票:1回答:2

我期望从服务器弹出错误代码403时,ServerHandler中的“ throw RuntimeException”会前进到registerAccount中的catch块,但是我无法捕获该错误...以下是我的代码:

LoginRepo.kt:

private fun registerAccount(context: Context, jsonObject: JSONObject, username: String, password: String): Result<LoggedInUser> {

    try {
        ServerHandler.getInstance(context).makeHttpRequest(
            "http://www.mywebpage.com/index.php",
            Request.Method.POST,
            jsonObject
        )

        return Result.Success(LoggedInUser(java.util.UUID.randomUUID().toString(), username))
    } catch (e: Throwable) {
        return Result.Error(IOException("Error registering account: ", e))
    }
}

ServerHandler.kt:

    @Throws(RuntimeException::class)
    fun makeHttpRequest(url: String, method: Int, jsonBody: JSONObject? = null):Any {
        // Instantiate the RequestQueue.
        Log.d("makeHttpRequest","Sending request!!!!")
        var stringRequest = when (method) {
            Request.Method.POST ->
                object : StringRequest(method, url,
                    Response.Listener<String> { response ->
                        Log.d("requestPOST", response)
                    }, Response.ErrorListener { error ->
                        @Throws(RuntimeException::class)
                        when(error.networkResponse.statusCode) {
                            403 -> {
                                throw RuntimeException("Username is taken.") //<--RuntimeException
                            }
                            else-> {
                                Log.d("UNHANDLED ERROR:", error.toString())
                            }
                        }})
                    }
       }

错误:

java.lang.RuntimeException: Username is taken.
    at com.example.inspire.data.ServerHandler$makeHttpRequest$stringRequest$5.onErrorResponse(ServerHandler.kt:75)
rest android-studio exception kotlin android-volley
2个回答
1
投票
我不知道所有详细信息,但似乎调用ServerHandler.getInstance(context).makeHttpRequest(必须立即返回(甚至在发出任何HTTP请求之前)。

只需在调用后放置一个日志记录语句,但在return之前也可以查看是否确实如此。当registerAccount函数已很长但已退出时(可能在其中定义了try / catch块),HTTP请求可能稍后在某个点(可能在另一个线程中)发出。


1
投票
由于Volley回调中的异步功能,Android Studio调试器已帮助确认makeAccount()在makeHttpRequest()完成与PHP服务器的通信之前返回了结果。
© www.soinside.com 2019 - 2024. All rights reserved.