Handling API errors gracefully in services

Loading

What You’ll Learn:

Why handling API errors properly is important
How to implement error handling in AngularJS services
Using $http interceptors for global error handling
Best practices for managing errors gracefully


1️⃣ Why Handle API Errors Gracefully?

When making API calls, errors will occur due to:
✅ Server downtime
✅ Network issues
✅ Incorrect API response
✅ Authentication failures

Instead of breaking the application, we should:
✔️ Catch errors and display meaningful messages
✔️ Provide fallback values
✔️ Log errors for debugging


2️⃣ Basic Error Handling in AngularJS Services

When using $http in a service, handle errors using .catch().

Example: API Call Without Error Handling

app.factory("ApiService", function ($http) {
return {
getData: function () {
return $http.get("/api/data"); // No error handling here
}
};
});

Problem: If this API fails, the app might crash or display nothing.


Solution: Handle Errors Using .catch()

Modify the service to catch errors and return a fallback response.

app.factory("ApiService", function ($http) {
return {
getData: function () {
return $http.get("/api/data")
.then(response => response.data) // Return response data
.catch(error => {
console.error("API Error:", error);
return { message: "Failed to fetch data" }; // Fallback data
});
}
};
});

What Happens?
✔️ If the API succeeds → return the actual response
✔️ If the API fails → return { message: "Failed to fetch data" } instead of breaking the app


3️⃣ Handling API Errors in Controllers

When calling a service in a controller, handle errors at the UI level.

app.controller("MainController", function ($scope, ApiService) {
ApiService.getData().then(function (data) {
$scope.data = data;
}).catch(function () {
$scope.errorMessage = "Could not load data. Please try again later.";
});
});

🔹 If API works: data is shown
🔹 If API fails: errorMessage is displayed in the UI


4️⃣ Using $http Interceptors for Global Error Handling

Instead of handling errors in every service, use $http interceptors to catch errors globally.

Step 1: Create an Interceptor

app.factory("ErrorInterceptor", function ($q) {
return {
responseError: function (rejection) {
console.error("HTTP Error:", rejection);

let errorMessage = "An error occurred. Please try again later.";

// Customize error messages based on status codes
if (rejection.status === 404) {
errorMessage = "Requested data not found!";
} else if (rejection.status === 500) {
errorMessage = "Internal server error!";
}

return $q.reject({ message: errorMessage });
}
};
});

How it Works?
✔️ Captures all failed HTTP requests
✔️ Modifies error messages based on status codes


Step 2: Register the Interceptor

Add it to $httpProvider so it applies to all requests.

app.config(function ($httpProvider) {
$httpProvider.interceptors.push("ErrorInterceptor");
});

Step 3: Use the Interceptor in a Service

Now, any service using $http automatically receives handled errors.

app.factory("ApiService", function ($http) {
return {
getData: function () {
return $http.get("/api/data")
.then(response => response.data)
.catch(error => {
console.log("Handled Error:", error.message);
return { message: error.message }; // Safe fallback
});
}
};
});

Why is this Useful?
Reduces duplicate error handling in every API call
Ensures consistent error messages across the app


5️⃣ Showing API Errors in UI Gracefully

Modify the HTML to show errors without breaking the page.

<div ng-controller="MainController">
<div ng-if="errorMessage" class="error">
<p>{{ errorMessage }}</p>
</div>

<div ng-if="!errorMessage">
<h2>Data Loaded</h2>
<p>{{ data.message }}</p>
</div>
</div>

🔹 If API fails → Shows error message
🔹 If API works → Displays data normally

Leave a Reply

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