When working with APIs in AngularJS, handling responses and errors properly is crucial for ensuring a smooth user experience. The $http
service in AngularJS provides methods like .then()
and .catch()
to manage success and error responses efficiently.
1. Understanding API Responses in AngularJS
Whenever an API request is made using $http
, the response contains:
data
– The actual response body from the server.status
– HTTP status code (e.g.,200
,404
,500
).headers
– Response headers.config
– Configuration details of the request.
Example: Handling a Successful API Response
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
console.log("Success:", response.data);
})
.catch(function(error) {
console.error("Error:", error);
});
Best Practice: Always check response.data
before using it.
2. Handling API Errors
Errors can occur due to:
- Client-side issues (e.g., incorrect request format)
- Server errors (e.g., internal server failure)
- Network problems (e.g., connection timeout)
Example: Handling API Errors with .catch()
$http.get("https://jsonplaceholder.typicode.com/posts/invalid")
.then(function(response) {
console.log("Data received:", response.data);
})
.catch(function(error) {
console.error("Error occurred:", error.status, error.statusText);
});
Error Handling Tip: Display user-friendly error messages instead of raw API errors.
3. Using $http
with Custom Error Messages
Example: Categorizing Errors
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
console.log("Data received:", response.data);
})
.catch(function(error) {
if (error.status === 404) {
console.error("Error: Resource not found!");
} else if (error.status === 500) {
console.error("Error: Internal Server Error!");
} else {
console.error("Unexpected error:", error.statusText);
}
});
Use Case: Customize error messages based on the status code.
4. Retrying Failed API Requests
If an API request fails due to a temporary issue, retrying the request can help.
Example: Retrying on Failure
function fetchData(retries) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
console.log("Data received:", response.data);
})
.catch(function(error) {
if (retries > 0) {
console.warn("Retrying request...");
fetchData(retries - 1);
} else {
console.error("Failed after multiple attempts:", error.statusText);
}
});
}
fetchData(3); // Retries 3 times before failing
Use Case: Useful for handling temporary server issues.
5. Handling Global API Errors Using $httpInterceptor
Instead of handling errors in every API call, use $httpInterceptor
to manage all errors globally.
Example: Creating an $httpInterceptor
app.factory("errorInterceptor", function($q) {
return {
responseError: function(rejection) {
if (rejection.status === 401) {
alert("Unauthorized! Please log in.");
} else if (rejection.status === 500) {
alert("Server error! Please try again later.");
}
return $q.reject(rejection);
}
};
});
app.config(function($httpProvider) {
$httpProvider.interceptors.push("errorInterceptor");
});
Use Case: Centralized error handling for all API requests.
6. Displaying API Errors to Users
Example: Showing Error Messages in the UI
<div ng-controller="MyController">
<p ng-if="errorMessage" style="color: red;">{{ errorMessage }}</p>
<ul>
<li ng-repeat="post in posts">{{ post.title }}</li>
</ul>
</div>
app.controller("MyController", function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.posts = response.data;
})
.catch(function(error) {
$scope.errorMessage = "Failed to load data. Please try again.";
});
});
Best Practice: Use ng-if
to display error messages dynamically.
7. Logging API Errors for Debugging
Example: Sending Errors to a Logging Service
app.factory("LoggingService", function($http) {
return {
logError: function(error) {
return $http.post("/log-error", { error: error });
}
};
});
app.controller("MyController", function($scope, $http, LoggingService) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.catch(function(error) {
console.error("Error:", error);
LoggingService.logError(error);
});
});
Use Case: Track API failures for troubleshooting.