我目前正在构建一个基于Laravel和VueJS的单页面应用程序。
有没有比我的更好的方法用axios来处理错误?
当用户点击登录按钮时,我就是这样做的:
VueTemplae:
methods : {
authenticateUser() {
axios.post('/api/login', this.form).then(() => {
this.$router.push({name : 'home'});
}).catch((error) => {
this.error = error.response.data.message;
});
}
}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');
}不幸的是,抛出异常总是会在控制台中打印一个内部服务器错误。
如果我返回的不是异常,axios总是执行then()。
有没有什么方法可以避免这种情况,或者有更好的方法来处理axios响应?
谢谢!
发布于 2021-02-17 23:53:54
您的API需要返回一个带有4XX状态代码的响应,以便在Vue组件中触发catch块。
示例:在API端捕获错误后,发送状态码为400 Bad Request的响应。它的格式将类似于您的成功登录响应,但带有错误消息和400状态代码,而不是200。
https://stackoverflow.com/questions/66243298
复制相似问题