代码之家  ›  专栏  ›  技术社区  ›  Rey Young

LaravelVue:如何使用Try-Catch块在验证请求中捕获验证异常?

  •  1
  • Rey Young  · 技术社区  · 7 年前

    我在用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 它起作用了。但不能让它与 Validation Request object .

    在我的控制器中:“ProductRequest”是具有验证规则的验证对象。它给了我错误,但在 axios 在VUE中。

     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块”中捕获它?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Maraboc    7 年前

    尝试如下:

    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);
        }
      });
    
    推荐文章