我创建了这个类,它使用axios的各种方法来检索/发送数据。这将是后续子类的父类,它将使用常规方法使事情变得更干净。
我将在下面发布整个文件,但我强调了我得到的一些类型错误,希望有人可以帮助。
我认为错误是隐含的any
或unknown
,所以我很惊讶我甚至得到这个错误。
import {
AxiosInstance,
AxiosResponseHeaders,
AxiosRequestConfig,
AxiosResponse,
AxiosError,
} from 'axios'
interface ErrorResponse {
data: null
status: number
statusText: string
headers: AxiosResponseHeaders
config: AxiosRequestConfig
}
interface PayloadType<T> {
[key: string]: T
}
export default class Axios {
axios: AxiosInstance = window.axios
async get<T>(route: string): Promise<T | ErrorResponse> {
try {
const { data } = await this.axios.get<T>(route)
return data
} catch (error) {
return this.handleErrorResponse<T>(error)
}
}
async post<T>(
route: string,
payload: PayloadType<T>
): Promise<T | ErrorResponse> {
try {
const { data } = await this.axios.post<T>(route, payload)
return data
} catch (error) {
return this.handleErrorResponse<T>(error)
}
}
async put<T>(
route: string,
payload: PayloadType<T>
): Promise<T | ErrorResponse> {
try {
const { data } = await this.axios.put<T>(route, payload)
return data
} catch (error) {
return this.handleErrorResponse<T>(error)
}
}
async patch<T>(
route: string,
payload: PayloadType<T>
): Promise<T | ErrorResponse> {
try {
const { data } = await this.axios.patch<T>(route, payload)
return data
} catch (error) {
return this.handleErrorResponse<T>(error)
}
}
async delete<T>(route: string): Promise<T | ErrorResponse> {
try {
const { data } = await this.axios.delete<T>(route)
return data
} catch (error) {
return this.handleErrorResponse<T>(error)
}
}
private handleErrorResponse<T>(error: AxiosError<T>): AxiosResponse<T> {
if (error.response) {
// The request was made, and the server responded with a status code
// that falls out of the range of 2xx
return error.response
} else if (error.request) {
// The request was made but no response was received, `error.request`
// is an instance of XMLHttpRequest in the browser and an instance
// of http.ClientRequest in Node.js
return {
data: null,
status: 0,
statusText: 'Network Error',
headers: {},
config: error.config,
}
} else {
// Something happened in setting up the request that triggered an Error
return {
data: null,
status: -1,
statusText: 'Unknown Error',
headers: {},
config: error.config,
}
}
}
}
1条答案
按热度按时间5cg8jx4n1#
需要检查错误示例的原因是,默认情况下它的类型为
unknown
,不能将其传递给handleErrorResponse
。或者你可以更新你的
handleErrorResponse
来接受unknown
值,这意味着你不必更新你的get
(和其他助手)。