To handle errors in an HTTP request in JavaScript, you can utilize the error handling capabilities of the XMLHttpRequest
object or the fetch
API. Here’s how you can handle errors using both methods:
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
} else {
console.log('Request failed with status:', xhr.status);
}
}
};
xhr.onerror = function() {
console.log('Request failed');
};
xhr.send();
In the above code, we handle errors by checking the status
property of the XMLHttpRequest
object inside the onreadystatechange
callback. If the status is 200, the request was successful, and we can parse the response. Otherwise, we log an error message with the status code. Additionally, we handle network errors by attaching an onerror
callback to the XMLHttpRequest
object.
Using the fetch API:
fetch('https://api.example.com/data')
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error('Request failed with status:', response.status);
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('Error:', error.message);
});
In the above code, we handle errors using the .catch
method on the Promise returned by the fetch
function. Inside the .then
method, we check if the response’s ok
property is true
. If it is, we parse the response as JSON. Otherwise, we throw an error with the status code. The error is caught by the .catch
method, where we log the error message.
By implementing error handling, you can gracefully handle errors and take appropriate actions based on the status or error message received during the HTTP request.