php - How to obtain response in Exception from Laravel into Kotlin
one text
I want to obtain the error messages from Laravel form request when i tried to register a new user in the system with invalid attributes, and use this messages on Kotlin to display them in the UI. The problem is when I tried to obtain this messages. For testing purpose first i just want to see the message and errors using Log.e():
response.body()?.message?.let { Log.e("error_message", it) }
response.body()?.validation_errors?.let { Log.e("error", it) }
First i overrided the failedValidation method on the custom Form request:
public function failedValidation(Validator $validator)
{
$errors = $validator->errors(); // Array of errors.
throw new HttpResponseException(response()->json([
'message' => 'Validation error',
'error' => (string)$errors->toJson()
], 422));
}
Here's the async call to the backend using retrofit in 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.
}
})
}
And the AuthResponse it defines like this:
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
)
Source