![]()
Error handling in $http requests is essential for building robust and reliable AngularJS applications. When making HTTP requests (GET, POST, PUT, DELETE), errors can occur for various reasons, such as network issues, server failures, incorrect responses, or bad requests. Proper error handling helps provide feedback to the user, log issues for debugging, and manage failed requests gracefully.
1. Basic Error Handling with $http
In AngularJS, $http returns a promise, and you can use .then() for handling successful responses and .catch() for errors. The .catch() method is specifically for handling errors in the promise.
Example: Basic Error Handling
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.getData = function() {
$http.get('/api/data')
.then(function(response) {
// Success handler
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
// Error handler
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
};
});
Explanation:
- Success Handler:
.then()is used to process the response from the server when the request is successful. - Error Handler:
.catch()is used to catch any errors that occur during the HTTP request. Theerrorobject contains information about the error.
2. Handling HTTP Status Codes
The $http service gives you access to the HTTP status codes in the response. You can use these status codes to perform custom error handling based on different types of errors, like 404 (not found), 500 (server error), etc.
Example: Handling Specific Status Codes
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.getData = function() {
$http.get('/api/data')
.then(function(response) {
// Success handler
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
// Error handler
console.error('Error occurred:', error);
if (error.status === 404) {
$scope.errorMessage = 'Data not found (404)';
} else if (error.status === 500) {
$scope.errorMessage = 'Internal server error (500)';
} else {
$scope.errorMessage = 'An unknown error occurred';
}
});
};
});
Explanation:
- You can check the
statusproperty of the error object to determine the HTTP status code and handle specific error scenarios, such as 404 (Not Found), 500 (Internal Server Error), or others.
**3. Global Error Handling Using $httpProvider
You can set up global error handling for all $http requests by configuring $httpProvider in your AngularJS application. This is useful for logging errors, setting default behaviors, or showing a global error message.
Example: Global Error Handling with $httpProvider
angular.module('myApp', [])
.config(function($httpProvider) {
// Add an interceptor to catch all errors globally
$httpProvider.interceptors.push('httpErrorInterceptor');
})
.factory('httpErrorInterceptor', function($q) {
return {
responseError: function(rejection) {
// This will catch errors from all $http requests
console.error('Global error occurred:', rejection);
return $q.reject(rejection);
}
};
})
.controller('MainController', function($scope, $http) {
$scope.getData = function() {
$http.get('/api/data')
.then(function(response) {
// Success handler
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
// Error handler
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
};
});
Explanation:
- Global Error Handler: The
httpErrorInterceptorintercepts any failed HTTP request and logs the error or handles it globally before passing it to the controller. - Response Error:
responseErroris invoked when an HTTP request fails. It can log errors, show notifications, or handle issues globally.
4. Handling Timeout Errors
You can configure $http to set a timeout for requests. If the request takes longer than the specified time, it will be aborted, and an error will be triggered. You can handle this using a timeout property in the $http request config.
Example: Timeout Error Handling
angular.module('myApp', [])
.controller('MainController', function($scope, $http, $timeout) {
$scope.getData = function() {
var config = {
timeout: 5000 // Timeout after 5 seconds
};
$http.get('/api/data', config)
.then(function(response) {
// Success handler
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
// Timeout error handling
if (error.status === -1) {
$scope.errorMessage = 'Request timed out';
} else {
$scope.errorMessage = 'An error occurred while fetching data.';
}
console.error('Error occurred:', error);
});
};
});
Explanation:
- Timeout: The
timeoutproperty specifies the number of milliseconds before the request should be aborted. - Error Handling: If the request times out, the
statusof the error object will be-1, and you can display a specific error message indicating that the request timed out.
5. Customizing the Error Object
When an error occurs, AngularJS’s $http provides a default error object that contains several useful properties, including status, statusText, data, and headers. You can customize how you handle the error depending on your application needs.
Example: Custom Error Object Handling
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.getData = function() {
$http.get('/api/data')
.then(function(response) {
// Success handler
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
// Custom error handling
console.error('Custom Error:', error);
// Use error.statusText and error.data for detailed messages
$scope.errorMessage = 'Error: ' + error.statusText + ' - ' + (error.data.message || 'Something went wrong');
});
};
});
Explanation:
- The
errorobject contains:status: HTTP status code (e.g., 404, 500).statusText: A string description of the HTTP status (e.g., “Not Found”).data: The response data (usually an error message or object).headers: The response headers.
You can use these properties to show more detailed error messages to the user.
