首页 > 解决方案 > 如何在从 Laravel 到 Kotlin 的异常中获取响应

问题描述

当我尝试在系统中注册具有无效属性的新用户时,我想从 Laravel 表单请求中获取错误消息,并在 Kotlin 上使用此消息在 UI 中显示它们。问题是当我尝试获取此消息时。首先出于测试目的,我只想使用 Log.e() 查看消息和错误:

response.body()?.message?.let { Log.e("error_message", it) }
response.body()?.validation_errors?.let { Log.e("error", it) }

首先,我在自定义表单请求上覆盖了 failedValidation 方法:

public function failedValidation(Validator $validator)
{
    $errors = $validator->errors(); // Array of errors.
    throw new HttpResponseException(response()->json([
        'message' => 'Validation error',
        'error' => (string)$errors->toJson()
    ], 422));
}

这是在 Kotlin 中使用改造对后端的异步调用:

val user = User(name, email, password, password_confirmation)
val call = request.register(user)

/** Async call */
call.enqueue(object : Callback<AuthResponse> {
    override fun onResponse(
        call: Call<AuthResponse>,
        response: Response<AuthResponse>
        ) {
            // It checks if status ~ 200
            if (response.isSuccessful) {
                //some code.
            } else {
                response.body()?.message?.let { Log.e("error_message", it) }
                response.body()?.validation_errors?.let { Log.e("error", it) }
            }
          }

          override fun onFailure(call: Call<AuthResponse>, e: Throwable) {
              //some code.
          }
    })
}

它定义的 AuthResponse 是这样的:

data class AuthResponse(
    var error: String? = null,
    var message: String? = null,
    var user: User? = null,
    var token: String? = null,
    var token_expires_at: Date? = null,
    var validation_errors: String? = null
)

标签: phpandroidlaravelkotlinretrofit

解决方案


推荐阅读