Last active
August 30, 2023 08:48
-
-
Save smitroshin/205661a13c0226ebf1acfbae60d1e0e8 to your computer and use it in GitHub Desktop.
Async + Await Error Handling Strategy using Axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AxiosError, AxiosResponse } from "axios"; | |
/** | |
* Axios types overload | |
*/ | |
export function asyncHelper<ResponseType = any, ErrorType = any>( | |
promise: Promise<AxiosResponse<ResponseType | ErrorType, any>> | null | undefined | false | |
): Promise<{ response: AxiosResponse<ResponseType> | null; error: AxiosError<ErrorType> | null }>; | |
/** | |
* Async helper | |
* | |
* Usage: | |
* | |
* const { response, error } = await asyncHelper(axios.get(...)); | |
* | |
* Source: https://youtu.be/wsoQ-fgaoyQ | |
*/ | |
export function asyncHelper<ResponseType = any, ErrorType = any>( | |
promise: Promise<ResponseType | ErrorType> | null | undefined | false | |
) { | |
return promise | |
? Promise.allSettled([promise]).then(([res]) => ({ | |
response: res.status === "fulfilled" ? res.value : null, | |
error: res.status === "rejected" ? res.reason : null, | |
})) | |
: Promise.resolve({ | |
response: null, | |
error: null, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment