如何使用 Axios 和 VueJS 捕获所有 Laravel API 错误?

How to catch all the Laravel API errors with Axios and VueJS?

更具体地说,我怎么能总是从我的 Laravel API 和 VueJS 运行 得到答案或不正确?因为如果后端有错误,我在前端没有答案。

这就是我使用 Axios、VueJS 和 sweetalert2 所做的事情:

axios.get('/usuarios').then(function(response){
   if(response.data.estatus == 'si'){
      Swal.fire('OK',response.data.mensaje,'success')
   }else{
      Swal.fire('Error',response.data.mensaje,'error')   
   }
})

如果控制器出现错误,我只会在控制台中收到错误,我如何捕捉它并使用 Sweetalert2 正确显示它?

例如:未捕获(承诺中)错误:请求失败,状态代码为 500

为了捕获 laravel 中的所有错误,您需要像这样编辑 App\Exceptions\Handler 文件

 public function render($request, Exception $exception)
{
    if ($exception){
        return response()->json([
            'status' => 'failed',
            'error' => $exception->getMessage()
        ]);
   }
    return parent::render($request, $exception); // return json with status => 'success' and 'message' => 'Done!'
}

然后在你的Vuejs项目中你可以很容易地找出后端发生的异常

axios.get('/usuarios').then(function(response){
   if(response.data.status == 'success'){
      Swal.fire('OK',response.data.message,'success') // or call another component
   }else{
      Swal.fire('Error',response.data.error,'error')   
   }
})