axios-exception-handler
Version:
Exception Handler for Axios
80 lines (57 loc) • 1.96 kB
Markdown
A lightweight utility for clean and customizable Axios error handling.
```bash
npm install axios-exception-handler
```
```bash
yarn add axios-exception-handler
```
Easily handle Axios errors with custom messages for specific HTTP status codes.
```typescript
import axios from "axios";
import { ExceptionHandler } from "axios-exception-handler";
const getHello = async ({ name }) => {
try{
const response = await axios.post<SignUpResponseBody>("/hello", {
name,
studentId,
phoneNumber,
});
} catch(err) {
ExceptionHandler(err)
.addCase(404, "Cannot Find User")
.addCase(409, "Conflict")
.addCases([500, 501, 503], "Server Error")
.addDefaultCase("Unexpected Error")
.handle();
}
return new ExceptionHandler(response)
};
// Usage
getHello()
.then((data) => {
console.log(data); // Hello name
})
.catch((err) => {
console.error(err); // 'Cannot Find User' | 'Conflict' | 'Server Error'
toast.error(err); // Render Toast From Derived Error
});
```
- **Custom Error Messages**: Map HTTP status codes to specific error messages.
- **Simple API**: Easily chain `addCase` or `addCases` methods.
- **TypeScript Support**: Fully typed for seamless integration.
**`addCase(code: number, message: string): this`**
Add a single HTTP status code to handle with a custom message.
**`addCases(codes: number[], message: string): this`**
Add multiple HTTP status codes to handle with the same custom message.
**`handle(): AxiosResponse<T> | Error`**
Throws an error with the custom message if the status code matches, otherwise returns the Axios response.
This project is licensed under the [ISC License](./LICENSE.md).