Handling JSON Responses and Errors

Tutorial 3 of 5

Handling JSON Responses and Errors

1. Introduction

This tutorial aims to guide you on how to handle JSON responses and errors when working with APIs in JavaScript. By the end of this tutorial, you should be able to parse JSON responses, handle errors properly, and implement best practices when dealing with API responses.

Prerequisites

  • Basic understanding of JavaScript
  • Familiarity with the JSON (JavaScript Object Notation) format
  • Basic knowledge of APIs and HTTP requests

2. Step-by-Step Guide

When working with APIs, you often send HTTP requests to a server and receive responses. These responses, often in JSON format, may contain useful data or error messages. Knowing how to parse and handle these responses is crucial in web development.

Parsing JSON Responses

When you receive a JSON response from an API, you can use JSON.parse() to convert it into a JavaScript object.

let jsonResponse = '{"name":"John", "age":30, "city":"New York"}';
let obj = JSON.parse(jsonResponse);
console.log(obj.name); // Outputs: John

Error Handling

If the server returns an error, you need to handle it properly. You can often find the error message in the JSON response. Always check the HTTP status code to determine whether the request was successful.

fetch('https://api.example.com/data')
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  } else {
    return response.json();
  }
})
.catch(error => {
  console.log('There was a problem with the fetch operation: ' + error.message);
});

3. Code Examples

Example 1: Fetching Data from an API

fetch('https://api.example.com/data')
  .then(response => response.json()) // Parse the JSON response
  .then(data => console.log(data)) // Use the data
  .catch(error => console.error('Error:', error)); // Handle errors

This example sends a request to https://api.example.com/data, parses the JSON response, and logs the result. If an error occurs during the fetch operation, it logs the error message.

Example 2: Handling HTTP Errors

fetch('https://api.example.com/data')
.then(response => {
  if (!response.ok) { // Check if the request was successful
    return response.json().then(error => throw new Error(error.message)); // If not, throw an error with the message from the JSON response
  }
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

This example handles HTTP errors by checking the status of the response. If the status is not OK, it throws an error with the error message from the JSON response.

4. Summary

  • We learned how to parse JSON responses with JSON.parse() and response.json().
  • We discussed how to handle errors by checking the HTTP status code and using catch().
  • We went over examples of fetching data from an API and handling HTTP errors.

Next, experiment with different APIs and try handling various types of errors. You might also want to explore libraries like axios that can simplify HTTP requests.

5. Practice Exercises

  1. Fetch data from the JSONPlaceholder API and log the title of each post.
  2. Extend the previous exercise by adding error handling. If the status code is not 200, throw an error with the status code.
  3. Fetch data from an invalid URL and handle the resulting error.

Solutions and explanations for these exercises can be found on the GitHub page. Remember, practice is the key to mastering any skill!