Lecture Notes Of Class 10: Error Handling in API Requests

Rashmi Mishra
0

 

Lecture Notes Of Class 10: Error Handling in API Requests

Objective:

The objective of this class is to teach you how to effectively handle errors and exceptions when working with APIs. APIs (Application Programming Interfaces) are widely used in web development to communicate with external services. When making API requests, it’s important to handle potential errors to ensure your application behaves gracefully, even when things go wrong.


Topics Covered:

1.  Checking HTTP Status Codes for Errors

2.  Handling Timeouts, Connection Failures, and Invalid Responses

3.  Logging Errors for Troubleshooting


1. Checking HTTP Status Codes for Errors

When you make a request to an API, the server responds with a status code that indicates whether the request was successful or if there was an error. These status codes are grouped into ranges:

·         2xx Success: These codes indicate that the request was successful.

    • 200 OK: The request was successful, and the server responded with the requested data.
    • 201 Created: The request was successful, and a new resource was created.

·         4xx Client Errors: These codes indicate that there was a problem with the request made by the client (your application).

    • 400 Bad Request: The server could not understand the request due to invalid syntax.
    • 401 Unauthorized: The client must authenticate itself to get the requested response.
    • 404 Not Found: The server could not find the requested resource.

·         5xx Server Errors: These codes indicate that the server failed to fulfill a valid request.

    • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
    • 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server.

Example in JavaScript (using fetch):

javascript
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      // Check if the response status is not OK
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log('Data received:', data);
  })
  .catch(error => {
    console.error('There was an error with the request:', error.message);
  });

In this example:

  • The fetch method sends a request to the API.
  • The response.ok property checks if the status code is between 200 and 299. If it's not, an error is thrown with the corresponding status code.
  • The catch block handles the error and logs it.

2. Handling Timeouts, Connection Failures, and Invalid Responses

Sometimes, the issue might not be with the API’s response, but with the network or the request itself. Here's how to handle those errors:

Timeout Errors:

When making API requests, it's possible that the request takes too long to complete. You can set a timeout to specify how long your application should wait for a response before considering it an error.

In JavaScript (using fetch with AbortController):

javascript
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);  // Set timeout for 5 seconds
 
fetch('https://api.example.com/data', { signal: controller.signal })
  .then(response => response.json())
  .then(data => {
    clearTimeout(timeoutId);  // Clear the timeout once the request is completed
    console.log('Data received:', data);
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.error('The request timed out.');
    } else {
      console.error('There was an error with the request:', error.message);
    }
  });

In this example:

  • We create an AbortController to control the request.
  • If the request takes longer than 5 seconds, the controller aborts it.
  • If the request times out, the error is caught, and the message "The request timed out" is displayed.

Connection Failures:

Connection failures can happen if the network is unavailable or if there is no response from the server. These failures are typically caught as network errors.

javascript
fetch('https://api.example.com/data')
  .then(response => response.json())
  .catch(error => {
    console.error('Network error: Could not connect to the API', error.message);
  });

Invalid Responses:

Sometimes, an API might return an invalid or malformed response. In such cases, it's important to check if the response can be parsed correctly.

javascript
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    if (data && typeof data === 'object') {
      console.log('Valid data:', data);
    } else {
      throw new Error('Invalid response data');
    }
  })
  .catch(error => {
    console.error('Error with the response:', error.message);
  });

In this case, we ensure the data is valid and can be processed. If it’s invalid (e.g., not a valid JSON object), we throw an error.


3. Logging Errors for Troubleshooting

When errors occur, logging them is essential for troubleshooting and fixing issues. In a production environment, you should log both the error message and additional context, such as the endpoint that failed and any relevant data.

Basic Logging:

For simple logging in the console, you can use console.error() to print the error details.

javascript
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .catch(error => {
    console.error('There was an error with the API request:', error);
    // Log additional details if necessary
    console.error('Failed to fetch data from https://api.example.com/data');
  });

Advanced Logging with External Services:

In a production environment, it's useful to log errors to an external service like Sentry or LogRocket, which will capture detailed logs, stack traces, and other helpful information to assist in debugging.

Example with Sentry:

javascript
import * as Sentry from "@sentry/browser";
 
Sentry.init({ dsn: "YOUR_SENTRY_DSN" });
 
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .catch(error => {
    console.error('Error with the API request:', error);
    Sentry.captureException(error);  // Log the error to Sentry for tracking
  });

By using services like Sentry, you can automatically capture and analyze errors in production, helping you to quickly identify and fix issues.


Summary

Error handling is an essential part of working with APIs to ensure that your application can handle unexpected situations gracefully.

  • Checking HTTP status codes allows you to identify errors related to the server or the request.
  • Handling timeouts, connection failures, and invalid responses ensures that your application doesn’t crash or hang when things go wrong.
  • Logging errors helps with troubleshooting by capturing useful information about the error and its context.

By handling errors effectively, you can make your application more reliable and easier to maintain, leading to a better experience for both developers and users.

You said:

WRITE SOME ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with explanation

ChatGPT said:

ChatGPT

Here are a few assignments based on the concept of Error Handling in API Requests, along with step-by-step solutions and explanations.


Assignment 1: Checking HTTP Status Codes for Errors

Problem Statement:

You are making a request to a weather API to get the current weather data. However, there is a chance that the request could fail due to various reasons (invalid endpoint, unauthorized access, etc.). Write a function to handle the request and check the status code for errors. If the status code indicates an error, display a specific error message.

Steps to Complete:

1.  Use the fetch API to send a request to the weather API (you can use a dummy endpoint for now).

2.  Check if the response status code indicates an error (i.e., anything outside the 2xx range).

3.  If there is an error, display an appropriate message, such as "Error: Invalid Request" for a 400 status or "Error: Unauthorized" for a 401 status.

Solution:

javascript
function fetchWeatherData() {
  fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=dummyapikey')
    .then(response => {
      if (!response.ok) {
        // Check if the status code is outside the 2xx range
        switch (response.status) {
          case 400:
            throw new Error('Error: Bad Request (400)');
          case 401:
            throw new Error('Error: Unauthorized (401)');
          case 404:
            throw new Error('Error: Not Found (404)');
          default:
            throw new Error(`Error: ${response.status}`);
        }
      }
      return response.json();
    })
    .then(data => {
      console.log('Weather data:', data);
    })
    .catch(error => {
      console.error(error.message);
    });
}
 
fetchWeatherData();

Explanation:

  • The fetchWeatherData function makes an API request to a weather service.
  • The response.ok property checks if the status code is in the 2xx range. If it's not, we handle specific errors based on the status code.
  • The error is thrown if the status code indicates an error (e.g., 400, 401, or 404), and the error message is displayed.
  • In case of success, we parse and display the weather data.

Assignment 2: Handling Timeouts in API Requests

Problem Statement:

You need to make an API request to fetch user data, but you must handle timeouts in case the server is slow or not responding within a reasonable time frame. The API request should timeout after 3 seconds and display a timeout error message.

Steps to Complete:

1.  Use AbortController to set a timeout for the fetch request.

2.  Set the timeout to 3 seconds.

3.  If the request takes longer than 3 seconds, abort the request and display a "Request Timeout" message.

Solution:

javascript
function fetchUserData() {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 3000);  // 3-second timeout
 
  fetch('https://jsonplaceholder.typicode.com/users', { signal: controller.signal })
    .then(response => response.json())
    .then(data => {
      clearTimeout(timeoutId);  // Clear the timeout when data is received
      console.log('User data:', data);
    })
    .catch(error => {
      if (error.name === 'AbortError') {
        console.error('Error: Request Timeout (3 seconds)');
      } else {
        console.error('Error:', error.message);
      }
    });
}
 
fetchUserData();

Explanation:

  • We create an AbortController to control the request and set a timeout of 3 seconds using setTimeout.
  • If the request takes longer than 3 seconds, the controller aborts the request, and an "AbortError" is thrown.
  • If the request completes before the timeout, the data is logged, and the timeout is cleared using clearTimeout.
  • If the request is aborted, a timeout message is displayed.

Assignment 3: Handling Network Failures

Problem Statement:

Sometimes, the client might not have an internet connection or the server might be unreachable. In this case, you should catch and display a "Network Error" message. Write a function to handle network failures when making a request to an API.

Steps to Complete:

1.  Use the fetch API to make a request to any available public API (you can use a dummy endpoint if necessary).

2.  Use a catch block to detect network errors, and display a "Network Error" message.

Solution:

javascript
function fetchData() {
  fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(data => {
      console.log('Received data:', data);
    })
    .catch(error => {
      if (error instanceof TypeError) {
        console.error('Error: Network Error. Unable to reach the API.');
      } else {
        console.error('Error:', error.message);
      }
    });
}
 
fetchData();

Explanation:

  • The fetchData function makes an API request to a placeholder service.
  • If the client is offline or if there is a connection issue, the catch block will handle the error.
  • TypeError is typically thrown for network-related errors (e.g., when the network is unavailable).
  • If any error occurs, an appropriate error message is displayed.

Assignment 4: Invalid JSON Response Handling

Problem Statement:

You are calling an API that returns JSON data. However, the API might return invalid or corrupted JSON. You need to handle this case and display a message indicating that the response is not valid JSON.

Steps to Complete:

1.  Make a fetch request to an API endpoint.

2.  Parse the response using response.json().

3.  If the response is not valid JSON, handle the error and display an error message.

Solution:

javascript
function fetchData() {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.text())  // Get the response as text first
    .then(text => {
      try {
        const data = JSON.parse(text);  // Attempt to parse the text as JSON
        console.log('Received data:', data);
      } catch (error) {
        throw new Error('Error: Invalid JSON Response');
      }
    })
    .catch(error => {
      console.error(error.message);
    });
}
 
fetchData();

Explanation:

  • In the fetchData function, we first use response.text() to get the raw response as text.
  • We then attempt to parse it as JSON using JSON.parse(). If the data is invalid JSON, a SyntaxError will be thrown.
  • The catch block will then handle this error and display the message "Error: Invalid JSON Response".

Assignment 5: Logging Errors for Troubleshooting

Problem Statement:

You are building an application where you need to make API requests to a remote server. You want to log errors for future troubleshooting. Write a function that logs errors to the console, and if the error is a network issue, logs additional details like the failed URL and request method.

Steps to Complete:

1.  Make a fetch request to an API.

2.  If an error occurs, log the error message and any additional information (such as the URL and request method).

3.  Log both network errors and API-specific errors with helpful details.

Solution:

javascript
function fetchData() {
  const url = 'https://jsonplaceholder.typicode.com/posts';
  const method = 'GET';
 
  fetch(url, { method })
    .then(response => {
      if (!response.ok) {
        throw new Error(`API Error: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      console.log('Received data:', data);
    })
    .catch(error => {
      if (error instanceof TypeError) {
        console.error(`Network error while fetching ${url} with method ${method}:`, error.message);
      } else {
        console.error('API request failed:', error.message);
      }
    });
}
 
fetchData();

Explanation:

  • The fetchData function attempts to fetch data from an API.
  • If the response is not OK (not a 2xx status code), an error is thrown with the status code.
  • If a network issue occurs, the error is detected as a TypeError and logged with the URL and method.
  • For API errors, the message is logged with a general error message indicating the failure.

Summary of Concepts Covered:

  • HTTP Status Codes: Understanding the different status codes and how to handle errors.
  • Timeouts and Network Failures: Handling timeouts and issues with connectivity.
  • Invalid Responses: Ensuring that the data you receive is in the correct format.
  • Logging: Capturing errors and logging useful information for troubleshooting.

These assignments give you hands-on practice with handling different types of errors when interacting with APIs.

You said:

WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation

ChatGPT said:

ChatGPT

Here are 50 multiple-choice questions (MCQs) based on the Error Handling in API Requests concept, along with explanations for the correct answers.


MCQs:

1.  What is the purpose of handling errors in API requests?

o    a) To display a success message

o    b) To ensure the application works correctly even when there are issues

o    c) To make the code more complex

o    d) To make the API faster

Answer: b) To ensure the application works correctly even when there are issues
Explanation: Handling errors ensures that even if the API request fails, the application can handle it gracefully and provide feedback to the user.

2.  What does the response.ok property in the Fetch API indicate?

o    a) The request was successful

o    b) The request was not successful

o    c) The request has not yet been sent

o    d) None of the above

Answer: a) The request was successful
Explanation: The response.ok property returns true if the HTTP status code of the response is in the range 200-299, indicating a successful request.

3.  Which of the following status codes indicates a "Bad Request"?

o    a) 404

o    b) 500

o    c) 400

o    d) 200

Answer: c) 400
Explanation: A status code of 400 indicates a "Bad Request," meaning that the client sent an invalid request.

4.  What does a 404 HTTP status code represent?

o    a) Not Found

o    b) Unauthorized

o    c) Bad Request

o    d) Internal Server Error

Answer: a) Not Found
Explanation: A 404 status code means that the requested resource could not be found on the server.

5.  Which HTTP status code indicates a successful request?

o    a) 301

o    b) 500

o    c) 200

o    d) 403

Answer: c) 200
Explanation: The 200 status code indicates that the request was successfully processed and the response is returned.

6.  How would you handle a 401 Unauthorized status in an API request?

o    a) Ask the user to log in

o    b) Retry the request without any changes

o    c) Show a "Page not found" message

o    d) Abort the request immediately

Answer: a) Ask the user to log in
Explanation: A 401 status code indicates that the user is unauthorized, so they must log in or provide valid credentials to proceed.

7.  In which situation would you use AbortController in JavaScript?

o    a) To handle a successful API response

o    b) To set a timeout for an API request

o    c) To parse a JSON response

o    d) To fetch data from a database

Answer: b) To set a timeout for an API request
Explanation: AbortController is used to abort a fetch request after a specified time, which is useful for handling timeouts.

8.  What happens if a fetch request takes longer than the specified timeout when using AbortController?

o    a) The request is automatically retried

o    b) An error is thrown with an "AbortError"

o    c) The request continues indefinitely

o    d) The request is logged

Answer: b) An error is thrown with an "AbortError"
Explanation: If the request takes too long, it is aborted, and an "AbortError" is thrown, indicating the timeout.

9.  Which method is used to cancel an ongoing fetch request using AbortController?

o    a) controller.abort()

o    b) controller.cancel()

o    c) controller.stop()

o    d) fetch.abort()

Answer: a) controller.abort()
Explanation: The abort() method of AbortController is used to cancel an ongoing request.

10.                   Which of the following is a valid way to check if the response from a fetch request is valid JSON?

o    a) response.json() without any error handling

o    b) response.text() and JSON.parse()

o    c) response.isValidJson()

o    d) response.json() && response.ok

Answer: b) response.text() and JSON.parse()
Explanation: Sometimes, you need to first convert the response to text and then manually parse it as JSON to check if it's valid.

11.                   What happens if the response from an API is not valid JSON?

o    a) The request is automatically retried

o    b) The response is discarded

o    c) A SyntaxError is thrown

o    d) The user sees a success message

Answer: c) A SyntaxError is thrown
Explanation: If the response is not valid JSON, attempting to parse it using JSON.parse() will throw a SyntaxError.

12.                   Which status code indicates that the server encountered an error while processing the request?

o    a) 400

o    b) 500

o    c) 302

o    d) 404

Answer: b) 500
Explanation: A 500 status code indicates a server-side error, meaning something went wrong while processing the request.

13.                   What is the purpose of response.ok in error handling for APIs?

o    a) To check if the request is still in progress

o    b) To check if the response was successful

o    c) To check if the response contains valid JSON

o    d) To validate the API endpoint

Answer: b) To check if the response was successful
Explanation: response.ok checks if the status code of the response is in the range of 200-299, indicating a successful response.

14.                   Which of the following HTTP status codes indicates that the resource was successfully created?

o    a) 200

o    b) 201

o    c) 400

o    d) 204

Answer: b) 201
Explanation: A 201 status code indicates that a new resource has been successfully created on the server.

15.                   What should you do if an API request fails due to a network error?

o    a) Retry the request multiple times

o    b) Show a generic error message to the user

o    c) Log the error for future troubleshooting

o    d) Ignore the error

Answer: c) Log the error for future troubleshooting
Explanation: Network errors should be logged so that developers can troubleshoot the issue later.

16.                   Which of the following methods is used to log errors in JavaScript?

o    a) console.alert()

o    b) console.log()

o    c) console.error()

o    d) console.notify()

Answer: c) console.error()
Explanation: console.error() is used to log error messages to the console.

17.                   Which status code represents "Forbidden" access to a resource?

o    a) 404

o    b) 403

o    c) 500

o    d) 301

Answer: b) 403
Explanation: A 403 status code means the server understood the request, but it refuses to authorize it.

18.                   What is a good practice when handling API errors in production?

o    a) Display the raw error message to users

o    b) Display a generic error message and log details for developers

o    c) Ignore the error and proceed with the next step

o    d) Show a blank page

Answer: b) Display a generic error message and log details for developers
Explanation: For security and user experience, display a friendly message while logging detailed error information for developers.

19.                   What would a 503 status code indicate in an API response?

o    a) Bad Request

o    b) Server Unavailable

o    c) Unauthorized Access

o    d) Not Found

Answer: b) Server Unavailable
Explanation: A 503 status code means the server is temporarily unavailable, usually due to maintenance.

20.                   In error handling, what should you do after catching an error in a promise chain?

o    a) Ignore the error and proceed

o    b) Handle the error and show a user-friendly message

o    c) Retry the request without changes

o    d) Trigger another request immediately

Answer: b) Handle the error and show a user-friendly message
Explanation: After catching an error, it’s important to handle it appropriately and provide useful feedback to the user.


(Continued in next part)

You said:

more 30

ChatGPT said:

ChatGPT

Here are the remaining 30 MCQs based on Error Handling in API Requests:


21.                   Which of the following is the proper way to catch errors in an asynchronous function?

  • a) Using catch() method
  • b) Using throw statement
  • c) Using try...catch block
  • d) Using finally block

Answer: c) Using try...catch block
Explanation: The try...catch block is used to handle errors in asynchronous functions and promises.

22.                   What is the purpose of the finally block in JavaScript error handling?

  • a) To catch errors
  • b) To log the errors
  • c) To execute code after the try block, regardless of whether an error occurred
  • d) To throw errors

Answer: c) To execute code after the try block, regardless of whether an error occurred
Explanation: The finally block is used to run cleanup code after try or catch blocks, regardless of whether an error was thrown.

23.                   What is a common error when making an API request with invalid JSON?

  • a) SyntaxError: Unexpected token
  • b) NetworkError: Request failed
  • c) TimeoutError: Request took too long
  • d) TypeError: Invalid URL

Answer: a) SyntaxError: Unexpected token
Explanation: If the server returns an invalid JSON response, attempting to parse it will cause a SyntaxError.

24.                   Which of the following is a common HTTP status code for "Method Not Allowed"?

  • a) 400
  • b) 405
  • c) 500
  • d) 404

Answer: b) 405
Explanation: A 405 status code indicates that the method used (GET, POST, etc.) is not allowed for the specified resource.

25.                   Which of these status codes is associated with server errors?

  • a) 300
  • b) 200
  • c) 500
  • d) 100

Answer: c) 500
Explanation: A 500 status code indicates a server error, which occurs when the server encounters an issue processing the request.

26.                   What should you do when an API response contains a 401 status code?

  • a) Retry the request with a new token
  • b) Show a "Server Error" message
  • c) Handle it as a successful request
  • d) Ignore the error

Answer: a) Retry the request with a new token
Explanation: A 401 status code means the user is unauthorized, often due to expired or invalid authentication tokens, so a new token should be provided.

27.                   Which of the following is an example of an API request timeout error?

  • a) Error: Timeout reached
  • b) Error: NetworkError
  • c) Error: ServerUnavailable
  • d) Error: Unauthorized

Answer: a) Error: Timeout reached
Explanation: When an API request takes longer than expected or defined timeout period, a timeout error occurs, often resulting in a message like "Timeout reached."

28.                   Which of the following techniques is used to prevent an API request from hanging indefinitely?

  • a) Using the finally block
  • b) Setting a timeout limit with AbortController
  • c) Using retry logic
  • d) Returning an error message to the user

Answer: b) Setting a timeout limit with AbortController
Explanation: The AbortController is used to set a timeout for API requests, helping to prevent requests from running indefinitely.

29.                   Which of these is a valid status code for "Internal Server Error"?

  • a) 404
  • b) 500
  • c) 503
  • d) 200

Answer: b) 500
Explanation: A 500 status code is used to indicate an internal server error, meaning the server encountered an unexpected condition.

30.                   When an API request fails, which status code typically suggests a missing resource?

  • a) 404
  • b) 400
  • c) 403
  • d) 301

Answer: a) 404
Explanation: A 404 status code means the requested resource could not be found on the server.

31.                   Which HTTP status code represents "Forbidden" access to a resource due to permissions?

  • a) 404
  • b) 400
  • c) 403
  • d) 401

Answer: c) 403
Explanation: A 403 status code means access to the resource is forbidden due to permission issues, even if authentication is provided.

32.                   In the context of error handling, what does a network error typically indicate?

  • a) The API server returned a response
  • b) There was an issue with the user's internet connection
  • c) The request was successful but with a warning
  • d) The response was invalid JSON

Answer: b) There was an issue with the user's internet connection
Explanation: A network error indicates that the request could not be completed due to issues such as no internet connection or DNS failure.

33.                   What is the most common way to log errors in JavaScript?

  • a) Using console.debug()
  • b) Using console.error()
  • c) Using console.log()
  • d) Using console.info()

Answer: b) Using console.error()
Explanation: console.error() is specifically designed to log error messages to the console.

34.                   Which function would you use to parse a JSON response from an API request in JavaScript?

  • a) JSON.decode()
  • b) JSON.parse()
  • c) JSON.parse()
  • d) JSON.encode()

Answer: b) JSON.parse()
Explanation: JSON.parse() is used to convert a JSON string into a JavaScript object.

35.                   What does the response.status property in JavaScript represent?

  • a) The status of the request in the fetch function
  • b) The status code of the HTTP response
  • c) Whether the response is successful or not
  • d) The data type of the response

Answer: b) The status code of the HTTP response
Explanation: response.status holds the HTTP status code returned by the server.

36.                   What should you do if you encounter a 500 status code while making an API request?

  • a) Retry the request immediately
  • b) Report the issue to the server admin
  • c) Check if the request parameters are correct
  • d) Continue with the application

Answer: b) Report the issue to the server admin
Explanation: A 500 status code typically indicates a server error, so it’s important to report it to the server admin or check server logs for issues.

37.                   Which of the following would most likely trigger a 400 HTTP status code?

  • a) Malformed request syntax
  • b) The server is down
  • c) The resource is not available
  • d) Unauthorized access

Answer: a) Malformed request syntax
Explanation: A 400 status code indicates a "Bad Request," meaning the request has invalid syntax or is otherwise incorrect.

38.                   Which error occurs when an API request is made to a server that doesn’t exist?

  • a) NetworkError
  • b) TimeoutError
  • c) NotFoundError
  • d) FetchError

Answer: a) NetworkError
Explanation: A NetworkError occurs when a request fails due to network issues, such as an invalid server or internet connection problems.

39.                   How can you handle a failed API request due to a timeout in JavaScript?

  • a) Retry the request
  • b) Use a finally block to clean up
  • c) Catch the error and show a message to the user
  • d) Both a and c

Answer: d) Both a and c
Explanation: On timeout, you can retry the request or show a user-friendly error message, depending on the application’s requirements.

40.                   How do you prevent repeated errors in API requests?

  • a) Always retry requests multiple times
  • b) Validate the request data before sending
  • c) Log the errors and ignore them
  • d) Use hard-coded error messages

Answer: b) Validate the request data before sending
Explanation: Ensuring the request is properly formatted and validated before sending can help prevent many errors from occurring.

41.                   Which of the following would NOT typically be handled in a catch block for an API request error?

  • a) Invalid JSON response
  • b) Timeout error
  • c) Successful response
  • d) Network error

Answer: c) Successful response
Explanation: A successful response does not require error handling, so it is not typically handled in a catch block.

42.                   Which JavaScript method would you use to abort an API request if it takes too long?

  • a) setTimeout()
  • b) clearTimeout()
  • c) AbortController.abort()
  • d) fetch.cancel()

Answer: c) AbortController.abort()
Explanation: The AbortController can be used to cancel or abort a request that is taking too long or needs to be stopped.


Let me know if you'd like to continue!

You said:

more 8

ChatGPT said:

ChatGPT

Here are the remaining 8 MCQs:


43.                   What does a 404 HTTP status code indicate in API error handling?

  • a) Server error
  • b) Bad request
  • c) Resource not found
  • d) Unauthorized access

Answer: c) Resource not found
Explanation: A 404 status code indicates that the requested resource could not be found on the server.

44.                   Which of the following would you typically log when handling API errors for debugging?

  • a) User’s personal information
  • b) Request parameters, response, and error details
  • c) Success messages
  • d) Only status codes

Answer: b) Request parameters, response, and error details
Explanation: For troubleshooting, it is important to log detailed information like request parameters, response data, and the error message to understand the issue.

45.                   How can you improve error handling for unreliable API services in production?

  • a) Using retry logic with exponential backoff
  • b) Ignoring errors to continue with the process
  • c) Only handling 500 errors
  • d) Continuously polling the API

Answer: a) Using retry logic with exponential backoff
Explanation: Exponential backoff helps handle temporary failures by progressively increasing the wait time between retry attempts, thus preventing overloading the server.

46.                   What type of error is typically associated with a 503 HTTP status code?

  • a) Service unavailable
  • b) Invalid request syntax
  • c) Forbidden access
  • d) Not found

Answer: a) Service unavailable
Explanation: A 503 status code indicates that the server is temporarily unavailable, often due to overloading or maintenance.

47.                   What does the response.ok property in a fetch request indicate?

  • a) The response is successful (status code 200-299)
  • b) The response is an error (status code 400-500)
  • c) The response was not received
  • d) The request is still pending

Answer: a) The response is successful (status code 200-299)
Explanation: The response.ok property is true if the status code is between 200 and 299, indicating a successful response.

48.                   What is the typical HTTP status code for a successful POST request?

  • a) 200
  • b) 201
  • c) 400
  • d) 500

Answer: b) 201
Explanation: A 201 status code indicates that a resource has been successfully created as a result of a POST request.

49.                   When handling API errors, why is it important to implement meaningful error messages?

  • a) To make the application look professional
  • b) To make it easier for users to understand what went wrong and how to fix it
  • c) To prevent errors from occurring
  • d) To increase server load

Answer: b) To make it easier for users to understand what went wrong and how to fix it
Explanation: Meaningful error messages help users understand the issue and, in some cases, how to resolve it, which improves user experience.

50.                   Which of the following would be a good practice for handling unexpected API errors?

  • a) Displaying a generic message to users (e.g., "Something went wrong")
  • b) Ignoring the error and continuing the process
  • c) Retrieving detailed user data and logging it
  • d) Not logging the error to avoid exposing sensitive information

Answer: a) Displaying a generic message to users (e.g., "Something went wrong")
Explanation: For unexpected errors, displaying a generic message to the user is best for security reasons, while logging the error internally for further analysis.

 

Tags

Post a Comment

0Comments

Post a Comment (0)