【发布时间】:2021-05-20 10:07:08
【问题描述】:
我目前正在构建一个基于 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 响应?
谢谢!
【问题讨论】:
-
catch阻止工作吗?我记得浏览器总是通知请求错误。你可以在catch块中做一些事情
标签: laravel vue.js authentication axios