When making AJAX requests and interacting with APIs, it's important to handle errors that may occur. Error handling allows you to gracefully handle any issues with the request or the API response.
A common way to handle errors in AJAX and API interactions is by using promises and the .catch()
method. Promises provide a way to handle both successful responses and errors in a more structured and predictable manner.
In the example code below, we make an AJAX request to an API endpoint using the fetch()
function. We then check the response status using the .ok
property. If the response status is 200
(indicating a successful request), we parse the JSON data. If the response status is not 200
, we throw an error with a custom message.
1const apiUrl = 'https://api.example.com/data';
2
3fetch(apiUrl)
4 .then(response => {
5 if (response.ok) {
6 return response.json();
7 } else {
8 throw new Error('Failed to fetch data.');
9 }
10 })
11 .then(data => {
12 // Process the data
13 })
14 .catch(error => console.error(error));
This code ensures that any errors in the AJAX request are caught and logged to the console. You can customize the error message and handle the error according to your application's requirements.
Proper error handling is essential for a robust and reliable application, as it helps identify and deal with any unexpected issues that may arise during AJAX and API interactions.
xxxxxxxxxx
const apiUrl = 'https://api.example.com/data';
fetch(apiUrl)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to fetch data.');
}
})
.then(data => {
// Process the data
})
.catch(error => console.error(error));