php - 如何在从 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
)
解决方案
推荐阅读
- swift - 在多个目标中重用本地 Swift 包
- node.js - Nginx 与 SSL 和 Frontend + Backend 相同的服务器
- java - Java - XML 反序列化
- android - Inkwell Widget 允许意外的区域点击
- php - 为什么默认的 WordPress 配置文件有 /**#@+ 之类的注释
- html - 在 MS Office URI 方案中使用非 ASCII 字符时出错
- django - 为什么 Django 上的“关注”按钮不起作用?
- ios - LPLinkView 隐藏信息视图
- excel - 如何基于 15 个字段连接 150 万行数据
- python - Python 在列表中查找重复出现的值(回测)