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

时间:2020-03-01 12:17:04

标签: rest android-studio exception kotlin android-volley

我期望从服务器弹出错误代码403时,ServerHandler中的“引发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)

2 个答案:

答案 0 :(得分:1)

我不知道所有详细信息,但是看来return调用必须立即返回(甚至在发出任何HTTP请求之前)。

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

答案 1 :(得分:1)

由于Volley回调中的异步功能,Android Studio调试器已帮助确认makeAccount()在makeHttpRequest()完成与PHP服务器的通信之前返回了结果。

随着registerAccount()返回,从makeHttpRequest()抛出RuntimeException(“ Usernametake ..”)的事件再也没有一个可以捕获其异常,这导致无法捕获该异常。

在这种情况下,捕获异常听起来是不可能的,所以我宁愿使 Toast.makeText( _context, “用户名已被使用!”, 吐司。LENGTH_LONG )。节目() 而不是抛出异常...