Handling Non-JSON Responses in Web Applications
When building web applications, it's crucial to handle various types of server responses gracefully. A common issue arises when an application expects a JSON response but receives something else, like an HTML page due to a session expiry or a CSRF mismatch. This can lead to cryptic errors and a poor user experience.
The Problem
Consider a scenario where a JavaScript-based modal sends an AJAX request to a server endpoint. The client-side code anticipates a JSON payload. However, if the user's session has expired, the server might redirect to a login page, returning HTML instead of JSON. Without proper handling, the JavaScript code will attempt to parse the HTML as JSON, resulting in an error.
Solution: Content-Type Checking
A robust solution involves checking the Content-Type of the response before attempting to parse it as JSON. If the Content-Type indicates HTML (or any non-JSON format), the application can display a user-friendly error message.
Here's an example of how to implement this in JavaScript:
fetch('example.com/api/data')
.then(response => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
} else {
throw new Error("Received non-JSON response");
}
})
.then(data => console.log(data))
.catch(error => {
console.error("Error:", error);
// Display user-friendly error message in the modal
displayErrorMessage("Session expired or invalid request. Please refresh the page.");
});
function displayErrorMessage(message) {
// Implementation to show the error message in the modal
alert(message);
}
This code snippet first fetches data from an API endpoint. It then checks the Content-Type header of the response. If the content type is application/json, it proceeds to parse the response as JSON. Otherwise, it throws an error, which is caught and used to display a user-friendly message in the modal.
Key Takeaway
Always validate the Content-Type of server responses before parsing them. This simple check can prevent cryptic errors and significantly improve the user experience, especially when dealing with potential session expirations or CSRF issues.