[英](VueJS, Axios) Different way to catch errors
I'm currently building a single page application based on Laravel and VueJS.我目前正在构建一个基于 Laravel 和 VueJS 的单页应用程序。
Is there any better way then mine to handle errors with axios?有没有比我更好的方法来处理 axios 的错误?
This is how I currently do it when a user clicks on login button:当用户单击登录按钮时,我目前是这样做的:
VueTemplae: VueTemplae:
methods : {
authenticateUser() {
axios.post('/api/login', this.form).then(() => {
this.$router.push({name : 'home'});
}).catch((error) => {
this.error = error.response.data.message;
});
}
}
Api route: Api路线:
public function login() {
try {
// do validation
} catch(Exception) {
// validation failed
throw new Exception('login.failed');
}
// manually authentication
if(Auth::attempt(request()->only('email', 'password'))) {
return response()->json(Auth::user(), 200);
}
// something else went wrong
throw new Exception('login.failed');
}
Unfortunately, throwing an exception always prints an internal server error into the console.不幸的是,抛出异常总是会将内部服务器错误打印到控制台中。
If I return something else than an exception, axios always executes then()
.如果我返回除异常以外的其他内容,则 axios 始终执行then()
。
Is there any way to prevent this or a better way to handle axios responses?有什么方法可以防止这种情况或更好的方法来处理 axios 响应?
Thank you!谢谢!
Your API needs to return a response with a 4XX status code in order for the catch block to fire in your Vue component.您的 API 需要返回带有 4XX 状态代码的响应,以便在您的 Vue 组件中触发 catch 块。
Example: After you catch the error on the API side, send a response with status code 400 Bad Request
.示例:在 API 端捕获错误后,发送状态码400 Bad Request
的响应。 It will be formatted similarly to your successful login response, but with an error message and 400 status code instead of 200.它的格式将与您成功的登录响应类似,但带有错误消息和 400 状态代码而不是 200。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.