Vue實(shí)戰(zhàn)(五)網(wǎng)絡(luò)層攔截器與全局異常信息展示

本文是Vue實(shí)戰(zhàn)系列的第五篇文章,主要介紹Falcon項(xiàng)目中網(wǎng)絡(luò)層攔截器與全局異常信息展示。Falcon項(xiàng)目地址:https://github.com/thierryxing/Falcon

全局Response處理

在處理網(wǎng)絡(luò)請(qǐng)求的過(guò)程中,我們通常要處理各種服務(wù)器返回的Response狀態(tài),一般情況下分為如下兩種:

  • Http本身的狀態(tài),通過(guò)狀態(tài)碼來(lái)區(qū)分,如:200,404,403,500等,下面是一個(gè)Response 504的錯(cuò)誤
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
  • 業(yè)務(wù)狀態(tài),一般都封裝在業(yè)務(wù)JSON中,然后由不同的值來(lái)區(qū)分,如:0(正確),1(錯(cuò)誤),下面是一個(gè)業(yè)務(wù)狀態(tài)的例子
{
    data: [],
    status: 0,
    message: ''
  }

其實(shí)無(wú)論是Http本身錯(cuò)誤狀態(tài)還是業(yè)務(wù)錯(cuò)誤狀態(tài),都是異常狀態(tài),對(duì)于業(yè)務(wù)層來(lái)說(shuō)都不重要,因?yàn)樗魂P(guān)心正確的返回值。

所以從架構(gòu)層面考慮,我們需要將這些異常狀態(tài)在底層統(tǒng)一處理,統(tǒng)一提示。這樣不但大大簡(jiǎn)化業(yè)務(wù)層的邏輯處理難度,業(yè)務(wù)層只需要處理正常邏輯即可;并且還可以方便未來(lái)的拓展。

比如:當(dāng)我們遇到網(wǎng)絡(luò)層異常時(shí),我們常常像下圖所示,彈出一個(gè)全局的提示,并且根據(jù)不同的錯(cuò)誤內(nèi)容,給予不同強(qiáng)度的樣式提示。

DingTalk20170717122017.png

Vue-Resource Interceptor

在Vue中,我們通常都會(huì)選擇Vue-Resource作為網(wǎng)絡(luò)層框架。這個(gè)框架非常友好的提供了一個(gè)網(wǎng)絡(luò)層的攔截器,通過(guò)這個(gè)攔截器,我們可以攔截所有Response,然后統(tǒng)一處理,其用法也很簡(jiǎn)單。

首先我們?cè)贏pp.vue的Created方法中創(chuàng)建攔截器:

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

然后,進(jìn)行各種Http狀態(tài),和業(yè)務(wù)狀態(tài)的判斷邏輯:

      handleResponse (response) {
        // 在處理前,刪除已經(jīng)彈出的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)
          }
        }
      },

最后增加對(duì)各種狀態(tài)的處理

      /**
       * 處理服務(wù)器Http請(qǐng)求異常
       * @param response
       */
      handleServerError (response) {
        this._showAlert(response.statusText)
      },

      ...

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

Alert組件

攔截到異常信息后,我們需要全局提示網(wǎng)絡(luò)狀態(tài),所以我們首先需要?jiǎng)?chuàng)建一個(gè)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>

由于這個(gè)Alert中需要接受全局的消息,然后通過(guò)消息來(lái)確定是否展示及展示什么樣的類型和內(nèi)容。
所以我們將消息的數(shù)據(jù)通過(guò)Vue Store進(jìn)行管理。

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
  }
}

...

當(dāng)Alert監(jiān)測(cè)到Store數(shù)據(jù)變化時(shí),顯示對(duì)應(yīng)的異常信息

<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. 全局網(wǎng)絡(luò)攔截器
  2. Alert組件
  3. Alert Store
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容