1. Axios异常处理器(axiosErrorHandler)

Axios异常处理器内置三种异常处理器:

  • 准备请求错误处理器(setUpRequestErrorHandler):用于处理准备请求时发生了某些导致错误的情况
  • 请求错误处理器(requestErrorHandler):用于处理请求已发送但为收到响应的情况
  • 响应错误处理器(responseErrorHandler):用于处理请求已发送但服务器返回了一个异常状态码的情况

目前上述三种处理器默认为处理逻辑为:调用 “axiosErrorHandler.logAxiosError” 将异常信息统一为平台的 Error 对象,然后通过日志管理器输出错误日志,最后抛出供业务代码处理并提示。

Axios错误日志

其中响应错误处理器还额外处理了 “403 Forbidden” 异常。

const responseErrorHandler = {
    handle(axiosError) {
        // 用于通知应用处理权限不够的异常,比如:跳转到购买更高权限套餐页面
        if (axiosError.response.status === 403) {
            eventBus.emit("EVENT_ACCESS_API_FORBIDDEN")
        }

        axiosErrorHandler.logAxiosError(axiosError)
    }
}

那么是否可以定制处理其它类型的业务异常呢?答案是肯定的!!!平台提供了可扩展的Axios异常处理机制。

1.1. 自定义Axios异常处理

Axios异常处理器实现了异常处理链,支持在上述三个内置处理器之间插入自定义的异常处理器,并可以添加自定义异常消息。 另外也可以覆盖内置处理器,直接采用自定义的异常处理器。

以处理 “503 Service Unavailable” 为例,实现了自定义异常处理器插件(customAxiosErrorHandler)。

const customAxiosErrorHandler = {
    name: "customAxiosErrorHandler",
    config: {},
    isAfterCoreInited: false, // 是否在内核初始化完成后初始化(可选,默认为:true)

    init(config) {
        this.config = config

        // 添加自定义异常信息
        const code = "ERR_SERVICE_UNAVAILABLE"
        axiosErrorHandler.addMessage(code, "服务端API不可用")

        // 自定义的业务异常处理器
        const customHandler = {
            name: "customResponseErrorHandler",
            getName() {
                return this.name
            },
            isSupport(axiosError) {
                return axios.isAxiosError(axiosError) && axiosError.request && axiosError.response;
            },
            handle(axiosError) {
                // 后端维护时通过ubp-ops-notice返回“503 Service Unavailable”
                if (axiosError.response.status === 503) {
                    // 修改错误码为自定义错误码
                    axiosError.code = code

                    // 省略具体的业务处理逻辑
                }
            }
        }
        // 在内置的响应异常处理器前插入自定义的业务异常处理器
        axiosErrorHandler.addHandlerBefore("responseErrorHandler", customHandler)
    }
}

export default customAxiosErrorHandler

其中:

  • 一个自定义异常处理器必须实现 “getName”、“isSupport”、“handle” 三个方法
  • “axiosErrorHandler.addHandlerBefore” 方法可以在指定名称的处理器之前插入自定义的异常处理
  • 另外 “axiosErrorHandler.addHandler” 方法可以添加同名的异常处理器,达到覆盖内置异常处理器的目的
  • “axiosErrorHandler.addMessage” 可以添加自定义错误码的异常消息,以便于 “axiosErrorHandler.logAxiosError” 输出友好的日志信息

最后注册该自定义异常处理器插件即可。

import App from "./App"
import customAxiosErrorHandler from "./sample/plugin/custom-axios-error-handler"

(async () => {
    // 创建应用
    const app = await createApp(App, [
            customAxiosErrorHandler
        ]
    )

    app.mount("#app")
})()

此时如果调用一个返回503状态码的后端服务,将会看到如下输出:

自定义Axios异常处理 Axios异常日志输出

Copyright ©zhoujianhui all right reserved,powered by Gitbook更新时间: 2024-10-25 15:20:11

results matching ""

    No results matching ""