[英]How to catch all the Laravel API errors with Axios and VueJS?
Being more specific, how can I always have an answer from my Laravel API with VueJS running or not correctly? 更具体地说,在VueJS运行还是不正确的情况下,如何始终能从Laravel API得到答案? Since if there is an error in the Backend I have no answer in the Frontend.
因为如果后端有错误,那么前端没有任何答案。
This is what I do with Axios, VueJS and sweetalert2: 这是我对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')
}
})
If an error arises in the controller I only get the error in console, how can I catch it and show it properly with Sweetalert2? 如果控制器中出现错误,我只会在控制台中收到错误,如何使用Sweetalert2捕获并正确显示它?
For example: Uncaught (in promise) Error: Request failed with status code 500 例如: 未捕获(承诺)错误:请求失败,状态码为500
for catch all errors in laravel you need to edit App\\Exceptions\\Handler file like this 为了捕获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!'
}
then in your Vuejs project easily you can find out exceptions that have occurred in the backend side 那么在您的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')
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.