52.前端页面显示服务器返回的异常

未匹配的标注

本节说明

  • 对应视频教程第 52 小节:Handling Server Exceptions with JavaScript

本节内容

此时,我们的检测机制已经工作正常。但是,我们的前端仍然需要做一些处理来正确地将服务器异常转换为给用户的反馈。我们将在本节解决这个问题。首先我们在后端捕获异常:
forum\app\Http\Controllers\RepliesController.php

    .
    .
    public function store($channelId,Thread $thread)
    {
        try{
            $this->validateReply();

            $reply = $thread->addReply([
                'body' => request('body'),
                'user_id' => auth()->id(),
            ]);
        }catch (\Exception $e){
            return response(
                'Sorry,your reply could not be saved at this time.',422
            );
        }

        return $reply->load('owner');
    }
    .
    .

我们以 422 的状态码返回异常,并提示 “Sorry,your reply could not be saved at this time.”现在如果我们进行不合法地回复:
file
在这里需要你运行以下命令确认一下Laravel-Mix的版本是否大于1.0

$ npm list --depth=0

如果不是,进行以下操作升级Laravel-Mix

$ rm -rf package-lock.json
$ rm -rf node_modules

接着修改composer.json里的"laravel-mix"的值:

"laravel-mix": "1.0.*"

接着需要重新安装Laravel-Mix,如果有疑问,可以翻看前面的章节。以下是我安装的依赖的版本:
file
现在我们已经在后端返回了异常,接下来我们需要在前端显示出来:
forum\resources\assets\js\components\NewReply.vue

    .
    .
    methods: {
            addReply() {
                axios.post(location.pathname + '/replies', { body:this.body })
                    .catch(error => {
                        console.log('ERROR');
                        console.log(error.response);
                    })
                    .then(({data}) => {
                       this.body = '';

                       flash('Your reply has been posted.');

                       this.$emit('created',data);
                    });
            }
        }
        .
        .

我们先打印出来error,看看具体信息:
file
然后我们显示出来:

    .
    .
    methods: {
            addReply() {
                axios.post(location.pathname + '/replies', { body:this.body })
                    .catch(error => {
                        flash(error.response.data);
                    })
                    .then(({data}) => {
                       this.body = '';

                       flash('Your reply has been posted.');

                       this.$emit('created',data);
                    });
            }
        }
        .
        .

现在我们尝试添加不合法回复:
file
消息内容显示正确,但是类型需要修改。接下来我们需要重写消息提示的方法:
forum\resources\assets\js\bootstrap.js

.
.
window.flash = function (message,level = 'success') {
    window.events.$emit('flash',{ message,level });
};

我们设置默认级别为success,根据传递的参数显示相应类型的消息。我们接着相应修改Flash.vue组件:
forum\resources\assets\js\components\Flash.vue

<template>
    <div class="alert alert-flash"
         :class="'alert-'+level"
         role="alert"
         v-show="show"
         v-text="body">
    </div>
 </template>

<script>
    export default {
        props:['message'],

        data(){
            return {
                body : '',
                level : 'success',
                show:false
            }
        },

        created(){
            if(this.message){
                this.flash(this.message);
            }

            window.events.$on(
                'flash',data => this.flash(data)
            );
        },

        methods:{
            flash(data){
                this.body = data.message;
                this.level = data.level;
                this.show = true;

                this.hide();
            },

            hide(){
                setTimeout( () => {
                   this.show = false;
                },3000);
            }
        }
    };
</script>

<style>
    .alert-flash{
        position: fixed;
        right: 25px;
        bottom: 25px;
    }
</style>

我们在NewReply.vue组件传递参数:
forum\resources\assets\js\components\NewReply.vue

.
.
flash(error.response.data,'danger');
.
.

我们现在再次尝试,消息类型正确显示为我们期望的类型:
file
接着我们显示编辑回复内容时捕获的异常:
forum\app\Http\Controllers\RepliesController.php

    .
    .
    public function update(Reply $reply)
    {
        $this->authorize('update',$reply);

        try{
            $this->validateReply();

            $reply->update(request(['body']));
        }catch (\Exception $e){
            return response(
                'Sorry,your reply could not be saved at this time.',422
            );
        }
    }
    .
    .

forum\resources\assets\js\components\Reply.vue

    .
    .
    methods:{
            update() {
                axios.patch('/replies/' + this.data.id,{
                        body:this.body
                    })
                    .catch(error => {
                        flash(error.response.data,'danger');
                    });

                this.editing = false;

                flash('Updated!');
            }
            .
            .

现在我们来尝试不合法更新回复:
file

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
发起讨论 查看所有版本


暂无话题~