Skip to content

Commit

Permalink
feat: 异常消息拦截器支持
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Apr 12, 2024
1 parent 80e7aab commit e012e1f
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 21 deletions.
29 changes: 23 additions & 6 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
import { useEffect } from 'react'
import { Button } from '@arco-design/web-react'
import { Button, Divider } from '@arco-design/web-react'
import apis from '@/apis'

function App() {
useEffect(() => {
const handleNormal = () => {
apis.user.fetchList()
.then((res: any) => {
.then((res) => {
console.log(res)
})
}, [])
}

const handleDataCodeError = () => {
apis.user.dataError()
.then((res) => {
console.log(res)
})
}

const handleHttpCodeError = () => {
apis.user.httpError()
.then((res) => {
console.log(res)
})
}

return (
<div style={{ padding: 16 }}>
<Button>点击</Button>
<Button onClick={handleNormal}>正常请求</Button>
<Divider />
<Button onClick={handleDataCodeError}>数据状态码异常请求</Button>
<Divider />
<Button onClick={handleHttpCodeError}>Http状态码异常请求</Button>
</div>
)
}
Expand Down
13 changes: 10 additions & 3 deletions example/src/apis/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ import { request } from '@pansy/request'

const prefix = 'users'

/**
* 获取请求列表
*/
export const fetchList = request({
method: 'get',
url: `${prefix}`
})

export const dataError = request({
method: 'get',
url: `${prefix}/data-error`
})

export const httpError = request({
method: 'get',
url: `${prefix}/http-error`
})
11 changes: 10 additions & 1 deletion example/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Message } from '@arco-design/web-react'
import { initializeInstance } from '@pansy/request'
import App from './App.tsx'
import './server'

initializeInstance({
baseURL: '/api',
timeout: 60 * 1000
timeout: 60 * 1000,
errorConfig: {
errorHandler: (data, error) => {
console.log('error', error)
if (data && data.message) {
Message.error(data.message)
}
}
}
})

ReactDOM.createRoot(document.getElementById('root')!).render(
Expand Down
35 changes: 34 additions & 1 deletion example/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { proxy } from 'ajax-hook';

proxy({
onRequest: (config, handler) => {
console.log(config)
if (config.url === '/api/users') {
handler.resolve({
config,
Expand All @@ -11,6 +10,7 @@ proxy({
'content-type': 'application/json'
},
response: {
success: true,
code: 0,
data: [],
message: 'success'
Expand All @@ -19,6 +19,39 @@ proxy({
return;
}

if (config.url === '/api/users/data-error') {
handler.resolve({
config,
status: 200,
headers: {
'content-type': 'application/json'
},
response: {
success: false,
code: 100001,
data: [],
message: '这是一个数据状态码异常'
}
})
return;
}

if (config.url === '/api/users/http-error') {
handler.resolve({
config,
status: 400,
headers: {
'content-type': 'application/json'
},
response: {
success: false,
code: 100002,
message: '这是一个 Http 状态码异常'
}
})
return;
}

handler.next(config)
}
})
29 changes: 29 additions & 0 deletions src/interceptor/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { AxiosResponse } from '../types'
import type { Interceptor } from './types'

/**
* 全局消息提示
*/
const errorMessageHandler: Interceptor = {
request: {},
response: {
onFulfilled: (response: AxiosResponse) => {
const { config, headers } = response

if (headers['content-type'].includes('application/json')) {
if (response.data?.success === false && config?.errorConfig?.errorHandler)
config?.errorConfig?.errorHandler(response.data)
}

return response
},
onRejected: (error) => {
const { config, response } = error

config?.errorConfig?.errorHandler?.(response?.data, error)
throw error
},
},
}

export default errorMessageHandler
6 changes: 5 additions & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ import axios from 'axios'
import { assign } from 'radash'
import type { AxiosInstance } from 'axios'
import urlArgsInterceptor from './interceptor/urlArgs'
import errorMessageInterceptor from './interceptor/error'

import type { Request, RequestConfig } from './types'
import type { Interceptor } from './interceptor/types'

let initializeConfig: RequestConfig = {}
const defaultInterceptors = [urlArgsInterceptor]
const defaultInterceptors = [
urlArgsInterceptor,
errorMessageInterceptor,
]

interface CreateAxiosOptions {
/** 是否使用默认拦截器 */
Expand Down
16 changes: 7 additions & 9 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {
AxiosError,
AxiosRequestConfig as AxiosRequestConfigType,
AxiosRequestHeaders,
AxiosResponse as AxiosResponseType,
} from 'axios'

Expand All @@ -9,7 +10,11 @@ export enum ErrorShowType {
SILENT = 0,
}

export interface AxiosResponse<Payload = any, D = any> extends AxiosResponseType<ResponseData<Payload>, D> {}
export interface AxiosResponse<Payload = any, D = any> extends Omit<AxiosResponseType<ResponseData<Payload>, D>, 'config'> {
config: RequestConfig<Payload, D> & {
headers: AxiosRequestHeaders
}
}

/** 接口返回数据格式 */
export interface ResponseData<Payload = any> {
Expand Down Expand Up @@ -61,18 +66,11 @@ export interface RequestConfig<
> extends Partial<AxiosRequestConfig<Data, Params, Args>> {
/** 异常处理相关配置 */
errorConfig?: {
/** */
errorThrower?: (data: AxiosResponse<ResponseData<Payload>>) => void
/**
* 错误接收及处理
*/
errorHandler?: ErrorHandler<Data>
errorHandler?: (data: ResponseData<Payload>, error?: AxiosError<ResponseData<Payload>>) => void
}
/**
* 是否跳过异常处理
* @default false
*/
skipErrorHandler?: boolean
}

export interface Request {
Expand Down

0 comments on commit e012e1f

Please sign in to comment.