JavaScript HTML

Improved Error Handling for LinkedIn Share Modal in Landing Project

When integrating with external services, handling unexpected responses is crucial for a smooth user experience. In the devlog-ist/landing project, which I worked on, we improved the error handling for the LinkedIn share modal to provide more informative feedback to the user.

The Problem: Cryptic Error Messages

Previously, when the LinkedIn share modal received a non-JSON response from the server (e.g., an HTML error page due to an expired session or CSRF mismatch), the modal would display a cryptic JSON parse error. This was confusing and unhelpful for the user, offering no clear indication of what went wrong or how to resolve the issue.

The Solution: Handling Non-JSON Responses

To address this, I implemented a check to determine if the server response is valid JSON. If the response is not JSON, we now display a user-friendly error message that explains the potential issue. This provides a better user experience by giving the user actionable information.

Here's a simplified example of how the error handling logic works:

fetch('/linkedin/share')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text(); // Get the raw response text
  })
  .then(data => {
    try {
      const jsonData = JSON.parse(data);
      // Process the JSON data
      console.log(jsonData);
    } catch (error) {
      // Display a user-friendly error message
      console.error('Failed to parse JSON:', error);
      displayErrorMessage('There was an issue sharing to LinkedIn. Please try again or ensure you are logged in.');
    }
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
    displayErrorMessage('An unexpected error occurred. Please try again later.');
  });

function displayErrorMessage(message) {
  // Display the error message in the modal
  alert(message);
}

In this example, we first fetch data from the /linkedin/share endpoint. We then attempt to parse the response as JSON. If the parsing fails (due to the response not being JSON), we catch the error and display a user-friendly error message to the user.

The Result: Improved User Experience

By implementing this improved error handling, the LinkedIn share modal now provides a much better user experience. Users are no longer presented with cryptic JSON parse errors. Instead, they receive informative messages that help them understand and resolve the issue, leading to a smoother and more satisfying interaction with the application.

Improved Error Handling for LinkedIn Share Modal in Landing Project
Gerardo Ruiz

Gerardo Ruiz

Author

Share: