When working with APIs, developers often encounter authentication errors. These errors can arise due to various reasons, such as invalid credentials or expired tokens. Proper error handling is crucial for creating a robust application that can gracefully manage these situations. Below are three practical examples of handling authentication errors in API responses.
In this example, an application tries to access a secure endpoint using an invalid API key. Proper error handling allows the application to inform the user and prompt for a valid key.
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer InvalidApiKey'
}
})
.then(response => {
if (response.status === 401) {
throw new Error('Authentication failed: Invalid API Key. Please check your credentials.');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error.message);
});
401
indicates unauthorized access, which is a common response for invalid credentials.This example demonstrates how to handle an expired token error when attempting to access an API. The application should detect the error and initiate a token refresh process.
fetch('https://api.example.com/secure-data', {
method: 'GET',
headers: {
'Authorization': 'Bearer ExpiredToken'
}
})
.then(response => {
if (response.status === 403) {
// Token expired, refresh token
return refreshToken().then(newToken => {
return fetch('https://api.example.com/secure-data', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + newToken
}
});
});
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error.message);
});
function refreshToken() {
return fetch('https://api.example.com/refresh-token', {
method: 'POST',
body: JSON.stringify({ /* Refresh details */ }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => data.newToken);
}
403
indicates that the server understood the request but refuses to authorize it, often due to token expiration.refreshToken
function handles the process of obtaining a new token seamlessly.In this scenario, an API request is made without including the required authentication header. The application should handle this situation by notifying the user about the missing header.
fetch('https://api.example.com/user-profile', {
method: 'GET'
})
.then(response => {
if (response.status === 401) {
throw new Error('Authentication failed: Missing Authorization header. Please provide valid credentials.');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error.message);
});
401
status code is used to indicate that the request lacks valid authentication credentials.