我期望从服务器弹出错误代码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)
ServerHandler.getInstance(context).makeHttpRequest(
必须立即返回(甚至在发出任何HTTP请求之前)。只需在调用后放置一个日志记录语句,但在return
之前也可以查看是否确实如此。当registerAccount
函数已很长但已退出时(可能在其中定义了try
/ catch
块),HTTP请求可能稍后在某个点(可能在另一个线程中)发出。