Skip to content

flavglen/axios-error-handling

Repository files navigation

Axios Error Handling Demo

A React application demonstrating centralized error handling with Axios interceptors and Material-UI snackbars.

🚀 Features

  • Centralized Error Handling: All HTTP errors are handled in one place using Axios response interceptors
  • Automatic Error Display: Error messages are automatically shown via Material-UI snackbars
  • Comprehensive Error Types: Handles various HTTP status codes (400, 401, 403, 404, 500) and network errors
  • Modern UI: Built with React, TypeScript, Tailwind CSS, and Material-UI
  • Error Testing: Interactive buttons to test different error scenarios

🛠️ Tech Stack

  • React 18 with TypeScript
  • Vite for build tooling
  • Axios for HTTP requests
  • Material-UI for snackbar notifications
  • Tailwind CSS for styling
  • Lucide React for icons

📦 Installation

  1. Clone the repository:
git clone <repository-url>
cd axios-error-handling
  1. Install dependencies:
npm install
  1. Start the development server:
npm run dev
  1. Open your browser and navigate to http://localhost:5173

🏗️ Project Structure

src/
├── api/
│   ├── axiosInstance.ts    # Axios configuration with interceptors
│   └── userService.ts      # API service functions
├── components/
│   └── UserList.tsx        # Main component with error testing
├── context/
│   └── ErrorContext.tsx    # Error context and snackbar provider
├── snackbarUtils.ts        # Global snackbar utilities
└── App.tsx                 # Main app component

🔧 How It Works

Centralized Error Handling

The application uses a centralized error handling approach:

  1. Axios Interceptor: All HTTP errors are caught by the response interceptor in axiosInstance.ts
  2. Global Snackbar: The interceptor automatically displays error messages using Material-UI snackbars
  3. Error Context: The ErrorContext provides a global error display system
  4. Snackbar Utils: A utility system allows the interceptor to trigger snackbars from anywhere

Error Types Handled

  • 400 Bad Request: Input validation errors
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 500 Server Error: Internal server errors
  • Network Errors: Connection issues

🎯 Usage

Basic API Call

import { getUsers } from './api/userService';

try {
  const users = await getUsers();
  // Success handling
} catch (error) {
  // Error is automatically handled by interceptor
  // No need to manually show error messages
}

Testing Different Errors

The application includes interactive buttons to test various error scenarios:

  • Fetch Users: Normal API call to JSONPlaceholder
  • 404 Error: Tests not found errors
  • 400 Bad Request: Tests validation errors
  • 401 Unauthorized: Tests authentication errors
  • 500 Server Error: Tests server errors
  • Network Error: Tests connection issues

🔄 Error Flow

  1. API Request → Axios instance
  2. Error Occurs → Response interceptor catches it
  3. Error Processing → Interceptor formats the error message
  4. Snackbar Display → Error message is automatically shown
  5. Promise Rejection → Error is still thrown for component handling

🎨 Customization

Adding New Error Types

To handle additional HTTP status codes, update the interceptor in axiosInstance.ts:

switch (error.response.status) {
  case 422:
    errorMessage = 'Validation Error: Please check your input';
    break;
  case 429:
    errorMessage = 'Too Many Requests: Please try again later';
    break;
  // Add more cases as needed
}

Customizing Error Messages

Modify the error messages in the interceptor to match your application's tone and requirements.

Styling

The application uses Tailwind CSS for styling. Modify the classes in components to change the appearance.

🧪 Testing

The application includes built-in error testing capabilities:

  1. Click "Fetch Users" to test successful API calls
  2. Use the error testing buttons to simulate different error scenarios
  3. Observe how errors are automatically displayed via snackbars

📝 Key Benefits

  • DRY Principle: No duplicate error handling code across components
  • Consistency: All errors are displayed uniformly
  • Maintainability: Error handling logic is centralized
  • User Experience: Automatic error feedback without manual intervention
  • Developer Experience: Components focus on business logic, not error handling

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

📄 License

This project is open source and available under the MIT License.

🙏 Acknowledgments

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published