让前端飞

Vue实战(五)网络层拦截器与全局异常信息展示

2017-07-19  本文已影响3817人  老邢Thierry

本文是Vue实战系列的第五篇文章,主要介绍Falcon项目中网络层拦截器与全局异常信息展示。Falcon项目地址:https://github.com/thierryxing/Falcon

全局Response处理

在处理网络请求的过程中,我们通常要处理各种服务器返回的Response状态,一般情况下分为如下两种:

Request URL:http://localhost:8080/api/projects?type=app&page=1
Request Method:GET
Status Code:504 Gateway Timeout
Remote Address:[::1]:8080
Referrer Policy:no-referrer-when-downgrade
{
    data: [],
    status: 0,
    message: ''
  }

其实无论是Http本身错误状态还是业务错误状态,都是异常状态,对于业务层来说都不重要,因为它只关心正确的返回值。

所以从架构层面考虑,我们需要将这些异常状态在底层统一处理,统一提示。这样不但大大简化业务层的逻辑处理难度,业务层只需要处理正常逻辑即可;并且还可以方便未来的拓展。

比如:当我们遇到网络层异常时,我们常常像下图所示,弹出一个全局的提示,并且根据不同的错误内容,给予不同强度的样式提示。

DingTalk20170717122017.png

Vue-Resource Interceptor

在Vue中,我们通常都会选择Vue-Resource作为网络层框架。这个框架非常友好的提供了一个网络层的拦截器,通过这个拦截器,我们可以拦截所有Response,然后统一处理,其用法也很简单。

首先我们在App.vue的Created方法中创建拦截器:

created () {
      Vue.http.interceptors.push((request, next) => {
        next((response) => {
          this.handleResponse(response)
          return response
        })
      })
    }

然后,进行各种Http状态,和业务状态的判断逻辑:

      handleResponse (response) {
        // 在处理前,删除已经弹出的Alert
        this.$store.dispatch('deleteAlert')
        if (response.status >= 400) {
          if (response.status === 401) {
            this.handleUnauthorized()
          } else if (response.status === 403) {
            this.handleForbidden()
          } else {
            this.handleServerError(response)
          }
        } else {
          if (response.data.status !== 0) {
            this.handleApiError(response)
          }
        }
      },

最后增加对各种状态的处理

      /**
       * 处理服务器Http请求异常
       * @param response
       */
      handleServerError (response) {
        this._showAlert(response.statusText)
      },

      ...

      /**
       * 向Store中分发需要弹出的消息
       * @param message
       * @private
       */
      _showAlert (message) {
        this.$store.dispatch('createAlert', {type: 'warning', message: message})
      }

Alert组件

拦截到异常信息后,我们需要全局提示网络状态,所以我们首先需要创建一个Alert组件,放置在全局模板中。

<template>
  <div class="skin-blue sidebar-mini wysihtml5-supported">
    <nav-bar></nav-bar>
    <side-bar></side-bar>
    <div class="content-wrapper" style="min-height: 916px;">
      <alert></alert>
      <div class="content">
        <router-view></router-view>
      </div>
    </div>
    <content-footer></content-footer>
  </div>
</template>

<script>

  ...

  import Alert from '@/components/global/Alert'
  export default {components: {SideBar, NavBar, ContentFooter, Alert}}
</script>

由于这个Alert中需要接受全局的消息,然后通过消息来确定是否展示及展示什么样的类型和内容。
所以我们将消息的数据通过Vue Store进行管理。

import * as types from '../mutation-types'
import storage from '@/utils/storage'

// initial state
const state = {
  alert: null
}

...

// mutations
const mutations = {
  [types.CREATE_ALERT] (state, alert) {
    state.alert = alert
  },

  [types.DELETE_ALERT] (state) {
    state.alert = null
  }
}

...

当Alert监测到Store数据变化时,显示对应的异常信息

<template>
  <div class="margin no-print" v-show="showAlert">
    <div class="alert alert-dismissible" :class="alertClass()">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
      <h4><i class="icon fa" :class="iconClass()"></i> {{ type }} </h4>
      {{ message }}
    </div>
  </div>
</template>

<script>

  import Vue from 'vue'
  import { mapGetters } from 'vuex'

  export default {
    computed: {
      ...mapGetters({
        alert: 'currentAlert'
      })
    },

    data () {
      return {
        showAlert: false,
        message: '',
        type: 'info'
      }
    },

    watch: {
      alert (alert) {
        if (alert !== null) {
          this.showAlert = true
          this.type = alert.type
          this.message = alert.message
        } else {
          this.showAlert = false
        }
      },

      $route () {
        this.$store.dispatch('deleteAlert')
      }
    },

   ...
  }
</script>

完整的例子

  1. 全局网络拦截器
  2. Alert组件
  3. Alert Store
上一篇下一篇

猜你喜欢

热点阅读