Handling Non-JSON Responses in a Modal
The Problem
When integrating with external services, unexpected responses can occur. In the devlog-ist/landing project, the LinkedIn share modal was designed to handle JSON responses from the server. However, in cases of session expiration or CSRF mismatches, the server would return an HTML error page instead. This resulted in a cryptic JSON parse error displayed to the user, providing a poor user experience.
The Approach
The solution was to implement error handling that gracefully handles non-JSON responses. The updated code checks the Content-Type of the response. If the response is not JSON, it displays a user-friendly error message within the modal.
Here's a simplified example of how such error handling might be implemented in JavaScript:
fetch('/example.com/share', { method: 'POST' })
.then(response => {
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Received non-JSON response');
}
return response.json();
})
.then(data => {
// Handle success
console.log('Success:', data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
displayErrorMessage('An unexpected error occurred. Please try again.');
});
function displayErrorMessage(message) {
// Implementation to display the error message in the modal
console.log(message);
}
This code snippet demonstrates a basic fetch request with error handling. It checks if the Content-Type header includes application/json. If not, it throws an error, which is then caught and a user-friendly message is displayed. The displayErrorMessage function is a placeholder for the actual implementation that updates the modal's content.
Key Insight
Robust error handling is crucial for a smooth user experience, especially when dealing with external services or APIs. By anticipating potential non-JSON responses and providing informative error messages, we prevent user confusion and frustration.