【问题标题】:Laravel-Vue: How can I use try-catch block to catch validation exception in Validation Requests?Laravel-Vue:如何使用 try-catch 块来捕获验证请求中的验证异常?
【发布时间】:2019-06-14 13:31:31
【问题描述】:

我正在使用 vue.js。我正在使用 axios 访问我的服务器,例如:

            try{
                const resp  = await axios.post('storeProduct', data, 
                            {
                                headers : header(state)
                            });
                console.log(resp);              

            }catch(error){
                console.log("you are at error");
                console.log(error);


           }

在这里,我在控制台记录错误,我收到错误 422,但我也想获得 message。如果我在一个简单的validation 中使用 try catch,它就可以工作。但不能让它与Validation Request object一起工作。

在我的控制器中:“ProductRequest”是具有验证规则的验证对象。它给了我错误,但无法在 vue 中 axios 的 try-block 中捕获。

 public function storeProduct(ProductRequest $request){

        try{
            return $controller->saveProducts($request);
        }catch(\Exception $e){
            return  $e;
        }

    }

ProductRequest.php

public function rules()
    {
        try{
            return validation_value('add_products');
        }catch(\Exception $e){
            return $e;
        }
    }

无论如何我可以从这里返回错误消息并在我的“vue axios try/catch 块”中捕获它

【问题讨论】:

  • 如果服务器返回异常,这可能是一个 500 代码,所以你可以这样做axios.post('storeProduct', data).catch(...)
  • 我想得到422 验证错误。我在我的网络上得到它,但无法在我的catch 上得到它。我捕捉到了422 错误,但没有捕捉到验证错误消息。
  • 在这种情况下,您不应该使用try catch,如果您使用 axios 承诺,则不需要等待。
  • 是的 axios 已经是一个承诺,但是为了使代码更短,我使用了 await... 这样做有问题吗,先生.. @thefallen

标签: laravel laravel-5 vue.js axios


【解决方案1】:

试试这样:

axios.post('storeProduct', data, 
        {
            headers : header(state)
        })
  .then(response => console.log(response.data))
  .catch(error => {
    if (error.response) {
      console.log("you are at error");
      console.log(error.response);
    }
  });

【讨论】:

  • 谢谢.. 你能帮我解决如何在 vue 中全局设置我的 axios 标头吗? {headers : {'Authorization': 'bearer' +state.token}});我在每个 axios 调用中发送标头
  • 看看这个answer的全局配置:)
猜你喜欢
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2011-01-11
相关资源
最近更新 更多