【发布时间】:2020-06-26 06:55:11
【问题描述】:
我正在尝试处理我的 Laravel/Vue 应用程序中的错误。据我所知,正如我所期望的那样,我已经准备好了一切。但是,如果响应不是200,我将无法获取/返回状态码。
console.log('status: ', response.status); // 200
如果响应是 400(或 200 以外的任何值),我将无法阅读。
console.log('status: ', response.status); // undefined
这是我在控制器中为响应创建的内容:
Controller.php
...
if ($exception->getCode() === 400) {
return response()->json(['errors' =>
[
'title' => 'Bad Request',
'detail' => 'The username or password you have entered is invalid',
],
], $exception->getCode());
}
在网络选项卡中,响应返回为400,响应对象如下所示:
{"errors":{"title":"Bad Request","detail":"The username or password you have entered is invalid"}}
太棒了!
我的 Vue 组件中的请求如下所示(点击事件处理程序):
...
try {
await this.$store.dispatch("user/signInWithEmailAndPassword", this.form)
.then(response => {
console.log('status: ', response.status);
switch (response.status) {
case 200:
console.log('good to go!');
break;
case 400:
console.log('400 error'); // not getting here
break;
case 401:
console.log('401 error'); // or here
break;
default:
console.log('some other error'); // end up here all the time
break;
}
})
.catch(error => {
console.log('SignInForm.authenticate error: ', error);
});
} catch (error) {
console.log("SignInForm.handleSubmit catch error:", error);
}
在我的 Vuex 商店中,我只是从我的服务返回响应以查看我得到了什么:
Vuex Store.vue
return await UserService.signInWithEmailAndPassword(credentials)
.then(response => {
return response;
...
UserService.vue
...
return await client.post('/v1/login', credentials)
.then(response => {
return response;
})
.catch(function (error) {
console.log('UserService.signInWithEmailAndPassword error: ', error); // getting here
return error;
});
到目前为止,我唯一的运气就是在我的控制台中看到这个:
UserService.signInWithEmailAndPassword 错误:错误:请求失败,状态码为 400
如何阅读400 错误代码以显示我真正想要的错误?似乎所有的碎片都在那里。我没有正确处理错误响应。感谢您的任何建议!
编辑
我已经更新了我的代码以反映您的建议,我相信这是因为没有正确返回我的 UserService 调用。这是我现在正在做的事情:
return await client.post('/v1/login', credentials)
.then(user => {
console.log('user: ', user);
return user;
})
.catch(function (error) {
console.log('error: ', error);
return error;
});
当我提供一个无效的 un/pw 时,我会陷入困境,并看到 error 消息:
错误:错误:请求失败,状态码为 400
虽然我没有正确归还它。例如,调用此方法的代码总是以.then 结尾,而不是.catch 块。
我觉得这是一件非常简单的事情,但我却让事情变得异常困难。感谢您的帮助!
【问题讨论】:
-
200 以外的任何东西都将被捕获块,因此,理想情况下,您的切换逻辑应位于捕获块中。
-
谢谢@ShivamSingh