使用 Axios 从 Laravel 控制器捕获错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49848519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:38:38  来源:igfitidea点击:

Capture error from laravel controller with Axios

jsonlaravellaravel-5vuejs2axios

提问by Felipe

?How i can capture errors from methos of controller in Laravel with Axios? The problem is the following, when the data passes through the validator of the myProfile method in the UserController in laravel and is correct, a json response is generated in the method and then Axios takes them and displays the toast Success message, but when i passes erroneous or empty data to the validor and this fails, Axios does not take the json with the error and shows me the empty toast and generates an error 422 in the console.

?如何使用 Axios 从 Laravel 中的控制器方法中捕获错误?问题如下,当数据通过laravel中UserController中myProfile方法的validator并且正确时,方法中生成一个json响应,然后Axios取下来显示toast成功信息,但是当我通过错误或空数据发送到验证器,这失败了,Axios 不接受带有错误的 json 并向我显示空的 toast 并在控制台中生成错误 422。

myProfile in User controller

用户控制器中的 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 section)

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);
            })
    }

Screenshot when Axios capture json Success fron controller

Axios 捕获json Success fron controller 时的截图

Screenshot when Axios capture Success request

Axios 捕获成功请求时的截图

Screenshot when Axios not capture json error from controller

Axios 未从控制器捕获 json 错误时的屏幕截图

Error

错误

Screenshot from console for json error no capture by axios

axios 未捕获 json 错误的控制台屏幕截图

Error 422 in console

控制台中的错误 422

?How i can solved that problem? I used Laravel 5.6, Vuejs 2 and Axios

?我怎么能解决这个问题?我使用了 Laravel 5.6、Vuejs 2 和 Axios

回答by fubar

If you wrap the validate()method call in a try/catchblock, then you can catch the ValidationExceptionthrown when the request is invalid. This will allow you to return your own response.

如果您将validate()方法调用包装在一个try/catch块中,那么您可以ValidationException在请求无效时捕获抛出的。这将允许您返回自己的响应。

I've shown you an example of this below, and included the validation errors too, should you wish to output these on the front-end.

如果您希望在前端输出这些,我在下面向您展示了一个示例,并且还包含了验证错误。

<?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);
    }
}