【问题标题】:How can I get the error status codes from a Vuex response?如何从 Vuex 响应中获取错误状态代码?
【发布时间】: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

标签: laravel vue.js axios


【解决方案1】:

then 在状态为status >= 200 && status < 300 时被调用。在catch 方法中捕获错误。上面的代码应该改成这样:

try {
    await this.$store.dispatch("user/signInWithEmailAndPassword", this.form)
        .then(response => {
            console.log('status: ', response.status);
            console.log('good to go!');
        })
        .catch(error => {
                switch (error.response.status) {
                    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;
                    }

            console.log('SignInForm.authenticate error: ', error);
        });
} catch (error) {
    console.log("SignInForm.handleSubmit catch error:", error);
}

当然你可以破坏错误,直接得到响应

.catch(({ response }) => {
                switch (response.status) {

更新

您还应该从服务中正确返回错误:

return await client.post('/v1/login', credentials)
        .then(user => {
            console.log('user: ', user);

            return user;
        })
        .catch(function (error) {
            console.log('error: ', error);

            return Promise.reject(error);
        });

【讨论】:

  • 我想我明白了——你的解释是一个巨大的帮助。我在 catch 块中添加了return Promise.reject(error);。你能把它包括在你的答案中,我会检查一下吗?这是一个很好的解释。
  • 我很高兴你已经弄清楚了。我已经更新了答案。
【解决方案2】:

您可以在您的 js 中添加一个 const 变量,以获取文件的内容,该文件返回一个 key->value 数组,然后从您的 js 访问它并显示错误消息。

配置文件示例:

return [
    "200" => "Todo bien",
    "201" => "Todo mal"
];

Vue 文件:

showItems()
{
    axios.get('shopping-cart').then(response => {

        if ( response.status != 200 ) return this.error = this.errors[response.status];
        this.items = response.data;

    }).catch(error => this.error = error);
}

【讨论】:

    猜你喜欢
    • 2020-01-10
    • 2013-02-27
    • 1970-01-01
    • 2021-09-06
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多