¿我如何使用Axios从Laravel中的控制器方法中捕获错误?问题如下,当数据通过laravel中的UserController中的myProfile方法的验证器并且是正确的时,在方法中生成json响应,然后Axios接收它们并显示toast Success消息,但是当我通过时错误或空数据到验证器,这失败了,Axios没有带错误的json,并向我显示空的toast并在控制台中生成错误422.
用户控制器中的myProfile
public function myProfile(Request $request)
{
$valido = $this->validate($request, [
'firstname' => 'required|min:3|max:15',
'lastname' => 'min:2|max:15',
'gender' => 'numeric',
'description' => 'max:200',
]);
if($valido){
return response()->json([
'status' => 'success',
'msg' => 'Ok',
], 201);
}
else{
return response()->json([
'status' => 'error',
'msg' => 'Error',
], 422);
}
}
Profile.vue(Axios部分)
updateUser(){
const value = {
'id': this.user.id,
'firstname': this.user.firstname,
'lastname': this.user.lastname,
'gender': this.user.gender,
'description': this.user.description,
}
axios.put('/dashboard/profile', value)
.then((response) => {
let title = response.data.status;
let body = response.data.msg;
this.displayNotificationSuccess(title, body);
})
.catch((error) => {
let title = error.response.data.status;
let body = error.response.data.msg;
this.displayNotificationError(title,body);
})
}
Axios捕获json成功控制器
时的屏幕截图Screenshot when Axios capture Success request
Axios未从控制器
捕获json错误时的屏幕截图控制台的屏幕截图,用于json错误,没有被axios捕获
¿我怎么能解决这个问题?我使用了Laravel 5.6,Vuejs 2和Axios
答案 0 :(得分:5)
如果将validate()
方法调用包装在try/catch
块中,则可以在请求无效时捕获ValidationException
抛出的内容。这将允许您返回自己的回复。
我已经向您展示了以下示例,如果您希望在前端输出这些错误,还会包含验证错误。
<?php
use Illuminate\Validation\ValidationException;
public function myProfile(Request $request)
{
try {
$this->validate($request, [
'firstname' => 'required|min:3|max:15',
'lastname' => 'min:2|max:15',
'gender' => 'numeric',
'description' => 'max:200',
]);
return response()->json([
'status' => 'success',
'msg' => 'Okay',
], 201);
}
catch (ValidationException $exception) {
return response()->json([
'status' => 'error',
'msg' => 'Error',
'errors' => $exception->errors(),
], 422);
}
}