Lesson 114 of 158 – Axios Error Handling
72%

Axios Error Handling

API requests can fail because of network problems, invalid data, authentication errors, server errors or unavailable APIs. Axios provides useful information that allows a React Native application to handle these errors properly.

Note: Good error handling should show a useful message to the user while keeping sensitive server and database details hidden.

1. Why Error Handling is Important

A mobile application depends on network communication. The API may not always respond successfully.

React Native
      ↓
    Axios
      ↓
 Network/API
      ↓
Success or Error
      ↓
 Handle Result
      ↓
      UI

2. Basic Axios Error Handling

try {

    const response =
        await axios.get(API_URL);

    console.log(
        response.data
    );

} catch (error) {

    console.log(
        error.message
    );
}

The catch block runs when Axios encounters an error.

3. Axios error.response

When the server responds with an HTTP error status, Axios usually provides the response through error.response.

catch (error) {

    console.log(
        error.response
    );

}

4. Reading the HTTP Status

catch (error) {

    console.log(
        error.response?.status
    );

}

For example, the API may return 400, 401, 403, 404, 422 or 500.

5. Reading the Error Response Data

catch (error) {

    console.log(
        error.response?.data
    );

}

A PHP API can return a structured JSON error message that React Native can display.

6. Reading the API Error Message

Suppose the API returns:

{
    "success": false,
    "message": "Student not found"
}

React Native can read the message using:

const message =
    error.response?.data?.message;

console.log(message);

7. Checking for a Server Response

catch (error) {

    if (error.response) {

        console.log(
            "Server responded"
        );

        console.log(
            error.response.status
        );

    }
}

This means the request reached a server and the server returned an HTTP response.

8. Network Error

A network error can happen when the device cannot communicate with the server.

catch (error) {

    if (!error.response) {

        console.log(
            "Network error"
        );
    }
}

Possible causes include no internet connection, an incorrect server URL, server downtime or connection problems.

9. error.request

Axios can provide information about the request when a request was made but no response was received.

catch (error) {

    if (error.request &&
        !error.response) {

        console.log(
            "No response received"
        );
    }
}

10. Axios error.message

catch (error) {

    console.log(
        error.message
    );

}

The message can help during development, but production applications should display a user-friendly message instead of exposing technical details.

11. Handling HTTP 400

HTTP 400 means the request is invalid or malformed.

catch (error) {

    if (
        error.response?.status === 400
    ) {

        setMessage(
            "Invalid request"
        );
    }
}

12. Handling HTTP 401

HTTP 401 indicates that authentication is required or the provided credentials/token are invalid.

if (
    error.response?.status === 401
) {

    setMessage(
        "Please login again"
    );
}

13. Handling HTTP 403

HTTP 403 means the user is authenticated or recognized but does not have permission to perform the requested operation.

if (
    error.response?.status === 403
) {

    setMessage(
        "You do not have permission"
    );
}

14. Handling HTTP 404

HTTP 404 means that the requested resource was not found.

if (
    error.response?.status === 404
) {

    setMessage(
        "Record not found"
    );
}

15. Handling HTTP 422

HTTP 422 is commonly used when the request format is understood but the submitted data fails validation.

if (
    error.response?.status === 422
) {

    setMessage(
        error.response.data?.message ||
        "Please check your input"
    );
}

16. Handling HTTP 500

HTTP 500 indicates a server-side error.

if (
    error.response?.status === 500
) {

    setMessage(
        "Server error. Please try again later."
    );
}

The server should log technical details instead of sending database or PHP error details to the mobile application.

17. Complete Status Handling

catch (error) {

    const status =
        error.response?.status;

    if (status === 400) {

        setMessage(
            "Invalid request"
        );

    } else if (status === 401) {

        setMessage(
            "Please login again"
        );

    } else if (status === 403) {

        setMessage(
            "Access denied"
        );

    } else if (status === 404) {

        setMessage(
            "Data not found"
        );

    } else if (status === 422) {

        setMessage(
            "Invalid data"
        );

    } else if (status >= 500) {

        setMessage(
            "Server error"
        );

    } else {

        setMessage(
            "Something went wrong"
        );
    }
}

18. Error State in React Native

const [errorMessage, setErrorMessage] =
    useState("");

try {

    const response =
        await axios.get(API_URL);

    setData(
        response.data.data
    );

    setErrorMessage("");

} catch (error) {

    setErrorMessage(
        "Unable to load data"
    );
}

19. Displaying an Error Message

{errorMessage !== "" && (

    <Text>
        {errorMessage}
    </Text>

)}

The user should receive a clear and simple message.

20. Retry After an Error

A retry button can be useful when a temporary network problem occurs.

async function loadStudents() {

    setErrorMessage("");

    try {

        const response =
            await axios.get(API_URL);

        setStudents(
            response.data.data || []
        );

    } catch (error) {

        setErrorMessage(
            "Unable to load students"
        );
    }
}
<Button
    title="Retry"
    onPress={loadStudents}
/>

21. Handling Authentication Errors

try {

    const response =
        await axios.get(
            PROFILE_URL,
            {
                headers: {
                    Authorization:
                        `Bearer ${token}`
                }
            }
        );

} catch (error) {

    if (
        error.response?.status === 401
    ) {

        // Clear local authentication
        // and navigate to login

        console.log(
            "Authentication expired"
        );
    }
}

22. Reusable Axios Error Function

function getApiErrorMessage(
    error
) {

    if (error.response) {

        return (
            error.response.data?.message ||
            "Server error"
        );

    }

    if (error.request) {

        return "No response from server";
    }

    return (
        error.message ||
        "Something went wrong"
    );
}

This function can be reused across multiple API screens.

23. Using the Reusable Error Function

try {

    const response =
        await axios.get(API_URL);

    setStudents(
        response.data.data || []
    );

} catch (error) {

    setErrorMessage(
        getApiErrorMessage(error)
    );
}

24. Error Handling with Loading State

async function loadStudents() {

    setLoading(true);
    setErrorMessage("");

    try {

        const response =
            await axios.get(API_URL);

        setStudents(
            response.data.data || []
        );

    } catch (error) {

        setErrorMessage(
            getApiErrorMessage(error)
        );

    } finally {

        setLoading(false);
    }
}

The finally block makes sure the loading state is reset whether the request succeeds or fails.

25. Complete Axios Error Handling Example

async function getStudents() {

    setLoading(true);
    setErrorMessage("");

    try {

        const response =
            await axios.get(
                API_URL
            );

        setStudents(
            response.data.data || []
        );

    } catch (error) {

        if (error.response) {

            const status =
                error.response.status;

            if (status === 401) {

                setErrorMessage(
                    "Please login again"
                );

            } else if (status === 403) {

                setErrorMessage(
                    "Access denied"
                );

            } else if (status === 404) {

                setErrorMessage(
                    "Students not found"
                );

            } else if (status === 422) {

                setErrorMessage(
                    "Invalid request data"
                );

            } else if (status >= 500) {

                setErrorMessage(
                    "Server error"
                );

            } else {

                setErrorMessage(
                    error.response.data?.message ||
                    "Request failed"
                );
            }

        } else if (error.request) {

            setErrorMessage(
                "No response from server"
            );

        } else {

            setErrorMessage(
                "Unable to complete request"
            );
        }

    } finally {

        setLoading(false);
    }
}

26. Complete PHP JSON Error Response

<?php

header(
    "Content-Type: application/json"
);

$id = filter_input(
    INPUT_GET,
    "id",
    FILTER_VALIDATE_INT
);

if (!$id) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Valid student ID is required"
    ]);

    exit;
}

try {

    // Database operation

} catch (PDOException $e) {

    error_log(
        $e->getMessage()
    );

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" =>
            "Internal server error"
    ]);

    exit;
}

Technical database errors should be logged on the server and not exposed to the mobile application.

27. Common Axios Error Handling Mistakes

  • Not using try...catch.
  • Ignoring HTTP status codes.
  • Showing raw server errors to users.
  • Displaying database errors to users.
  • Not handling network errors.
  • Not handling 401 authentication errors.
  • Not handling 403 authorization errors.
  • Not handling 404 errors.
  • Not handling 422 validation errors.
  • Not resetting loading state after an error.
  • Not providing a retry option when appropriate.

28. Complete React Native Error Screen

import React, {
    useEffect,
    useState
} from "react";

import {
    View,
    Text,
    Button,
    ActivityIndicator
} from "react-native";

import axios from "axios";

const API_URL =
    "https://example.com/api/students.php";

export default function StudentList() {

    const [students, setStudents] =
        useState([]);

    const [loading, setLoading] =
        useState(false);

    const [errorMessage, setErrorMessage] =
        useState("");

    async function loadStudents() {

        setLoading(true);
        setErrorMessage("");

        try {

            const response =
                await axios.get(API_URL);

            setStudents(
                response.data.data || []
            );

        } catch (error) {

            if (error.response) {

                const status =
                    error.response.status;

                if (status === 401) {

                    setErrorMessage(
                        "Please login again."
                    );

                } else if (status === 403) {

                    setErrorMessage(
                        "Access denied."
                    );

                } else if (status === 404) {

                    setErrorMessage(
                        "No student data found."
                    );

                } else if (status >= 500) {

                    setErrorMessage(
                        "Server error. Try again later."
                    );

                } else {

                    setErrorMessage(
                        error.response.data?.message ||
                        "Request failed."
                    );
                }

            } else if (error.request) {

                setErrorMessage(
                    "Please check your internet connection."
                );

            } else {

                setErrorMessage(
                    "Something went wrong."
                );
            }

        } finally {

            setLoading(false);
        }
    }

    useEffect(() => {

        loadStudents();

    }, []);

    return (

        <View style={{
            flex: 1,
            padding: 20
        }}>

            {loading && (
                <ActivityIndicator
                    size="large"
                />
            )}

            {errorMessage !== "" && (

                <View>

                    <Text>
                        {errorMessage}
                    </Text>

                    <Button
                        title="Retry"
                        onPress={loadStudents}
                    />

                </View>

            )}

            {!loading &&
             errorMessage === "" && (

                <Text>
                    Students loaded:
                    {students.length}
                </Text>

            )}

        </View>
    );
}

29. User-Friendly Error Messages

Technical Situation User Message
Network unavailable Please check your internet connection.
401 Please login again.
403 You do not have permission.
404 Requested data was not found.
422 Please check your entered information.
500 Server error. Please try again later.

30. Complete Axios Error Handling Flow

React Native
      ↓
   Axios Request
      ↓
   API Server
      ↓
 ┌───────────────┐
 │   Success?    │
 └───────────────┘
      ↓
   Yes / No
      ↓
Success → Display Data

Error
  ↓
Check response
  ↓
Check status
  ↓
401 / 403 / 404 / 422 / 500
  ↓
Show User-Friendly Message

No Response
  ↓
Network Error
  ↓
Retry

Proper Axios error handling makes React Native applications more reliable, easier to debug and more user-friendly.

📌 Key Points

  • Use try...catch to handle Axios errors.
  • error.response contains information when the server responds with an error.
  • error.response.status provides the HTTP status code.
  • error.response.data contains the API error response.
  • error.request can indicate that no response was received.
  • Handle network errors separately from server errors.
  • Handle 401 authentication errors properly.
  • Handle 403 authorization errors properly.
  • Handle 404, 422 and 500 errors appropriately.
  • Do not expose database or PHP technical errors to users.
  • Use loading, error and success states in React Native.
  • A retry option can help recover from temporary network failures.

🧠 Quick Quiz

Question: Which Axios property commonly contains the server response when an HTTP error occurs?