如何编写typescript异步axios?以及如何使用try/catch



我正在努力找出编写typescript异步axios请求的最佳方式。If每个函数都应该有自己的try/catch块吗?如果是,我应该如何键入函数结果?

对于try/catch块,类型为:Promise<ExpectedType | undefined>如果没有try/catch块,则类型为Promise<ExpectedType>

以下是示例:

async function v1(): Promise<ExpectedType> {
const response = await axios.get('https://...')
return response.data
}
async function v1Copy(): Promise<ExpectedType> {
const response = await axios.get('https://...')
return response.data
}
async function v2(): Promise<ExpectedType | undefined> {
try {
// I could use object destructuring for 'data' but ignore this for now
const response = await axios.get('https://...')
return response.data
} catch (e) {
// how to handle this safely
const error = e as AxiosError | Error
if (error instanceof AxiosError) {
if (error.response) {
console.error(`axios error: ${error.response.status} ${error.response.statusText}`)
} else {
console.error(`axios error: ${error.message}`)
}
} else {
console.error(`generic error: ${error.message}`)
}
}
}

现在,当我需要在代码的另一部分中使用v1 / v1Copy时,我必须将其封装在try-catch/catch块中。这是显而易见的。

最好的方法是什么?

...
try {
const v1Result = await v1()
const v1CopyResult = await v1Copy()
// use v1Result and v1CopyResult
} catch(e) {}

...
const v2Result = await v2()
if (typeof v2Result !== 'undefined') {
// here should be a typeguard, right?
// use v2Result
}

在同一个try/catch块中使用v1v1Copy可以吗?谢谢我正在努力寻找处理这件事的最佳方法,并理解原因。

我认为最好的方法是将每个函数封装在自己的try/catch块中,这样,如果promise被拒绝,整个代码就不会崩溃。

最新更新