Rest 无法捕获从另一个函数引发的异常
当错误代码403从服务器中弹出时,我希望ServerHandler中的“throw RuntimeException”继续执行registerAccount中的catch块,但我无法捕获错误。。。下面是我的代码: LoginRepo.kt:Rest 无法捕获从另一个函数引发的异常,rest,android-studio,exception,kotlin,android-volley,Rest,Android Studio,Exception,Kotlin,Android Volley,当错误代码403从服务器中弹出时,我希望ServerHandler中的“throw RuntimeException”继续执行registerAccount中的catch块,但我无法捕获错误。。。下面是我的代码: LoginRepo.kt: private fun registerAccount(context: Context, jsonObject: JSONObject, username: String, password: String): Result<LoggedInUser
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.getInstance(context).makeHttpRequest(
必须立即返回(甚至在发出任何HTTP请求之前)
只需在调用之后、返回之前放一条日志语句,看看是否真的是这样。HTTP请求可能是在稍后某个时间点发出的(可能是在另一个线程中),此时
registerAccount
函数已很长时间但已退出(其中定义的try
/catch
块也是如此)由于Volley回调中的异步功能,Android Studio调试器帮助确认registerAccount()在makeHttpRequest()完成与PHP服务器通信的工作之前已返回结果
当registerAccount()返回时,从makeHttpRequest()抛出RuntimeException(“Username已获取”)。没有人可以捕获其异常,这导致无法捕获异常
在这种情况下,捕获异常听起来是不可能的,所以我宁愿做一个
Toast.makeText(
_背景,
“用户名已被占用!”,
吐司,长度
).show()
不要抛出异常…LOL,特别是我刚才发现的,你比我快了16秒哈哈,这是值得接受的答案。听起来处理凌空的错误超出其范围是不可能的,因为凌空似乎不像JavaScript那样提供AJAX回调函数/承诺。
@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)