AXIN4 – Xử lý lỗi trong các yêu cầu HTTP
3 mins read

AXIN4 – Xử lý lỗi trong các yêu cầu HTTP

Bước 1: Tạo Axios Instance với Interceptor

Đầu tiên, chúng ta tạo một file axiosInstance.js để tạo một instance của Axios và thêm Interceptor để xử lý lỗi.

import axios from 'axios';

// Tạo instance của Axios với base URL
const axiosInstance = axios.create({
  baseURL: 'https://api.example.com',
});

// Thêm Interceptor cho các phản hồi
axiosInstance.interceptors.response.use(
  (response) => {
    // Xử lý phản hồi thành công
    return response;
  },
  (error) => {
    // Xử lý lỗi
    if (error.response) {
      // Server trả về phản hồi với mã trạng thái ngoài khoảng 2xx
      console.error('Response error:', error.response.data);
      alert(`Error: ${error.response.data.message}`);
    } else if (error.request) {
      // Yêu cầu được gửi đi nhưng không nhận được phản hồi
      console.error('Request error:', error.request);
      alert('Network error: No response received from server');
    } else {
      // Một lỗi khác đã xảy ra khi thiết lập yêu cầu
      console.error('Error:', error.message);
      alert(`Error: ${error.message}`);
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;

Bước 2: Sử dụng Axios Instance trong một React Component

Sau khi tạo instance của Axios với Interceptor, bạn có thể sử dụng nó trong các component React để thực hiện các yêu cầu HTTP và xử lý lỗi.

import React, { useEffect, useState } from 'react';
import axios from './axiosInstance';

const ErrorHandlingComponent = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('/data-endpoint');
        setData(response.data);
      } catch (error) {
        setError(error);
      }
    };

    fetchData();
  }, []);

  if (error) return <div>Error: {error.message}</div>;
  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default ErrorHandlingComponent;

Giải thích cấu trúc mã:

  1. Tạo Axios Instance:
    • axios.create({ baseURL: 'https://api.example.com' }): Tạo một instance của Axios với URL cơ bản.
    • axiosInstance.interceptors.response.use: Thêm Interceptor cho các phản hồi để xử lý lỗi.
  2. Interceptor cho các phản hồi:
    • Xử lý phản hồi thành công: return response: Trả về phản hồi thành công.
    • Xử lý lỗi:
      • error.response: Xử lý lỗi từ server (mã trạng thái ngoài khoảng 2xx).
      • error.request: Xử lý lỗi khi không nhận được phản hồi từ server.
      • error.message: Xử lý các lỗi khác khi thiết lập yêu cầu.
  3. Sử dụng Axios Instance trong Component:
    • useEffect: Dùng để thực hiện hàm fetchData ngay khi component được render.
    • axios.get('/data-endpoint'): Thực hiện yêu cầu GET tới endpoint /data-endpoint.
    • setData(response.data): Lưu dữ liệu trả về vào state data.
    • setError(error): Lưu lỗi nếu có xảy ra.
    • return <div>Data:</div>: Hiển thị dữ liệu khi đã tải xong.
    • return <div>Error: {error.message}</div>: Hiển thị lỗi nếu có.

Nguồn tham khảo:

Leave a Reply

Your email address will not be published. Required fields are marked *