guides
Error Handling
The News API returns various error codes and messages to indicate different types of errors that may occur. This guide provides a list of error codes and their corresponding descriptions to help you troubleshoot errors.
Error Codes
Status | Code | Description |
---|---|---|
400 | BAD_REQUEST | Your request is invalid. Check the API documentation for the correct parameters and format. |
400 | INVALID_COUNTRY_CODE | Invalid country code. Check the API documentation for the correct parameters and format. |
401 | UNAUTHORIZED | Your API key is invalid or not authorized to access this resource. |
429 | TOO_MANY_REQUESTS | You have exceeded your API rate limit. Wait a while and try again later. |
500 | SERVER_ERROR | Something went wrong on the server. Try again later. |
Error Responses
The News API returns errors in JSON format. The JSON response includes the status
and message
fields to help you identify the error.
Error Response
{ "status": 401, "message": "Unauthorized - Your API key is invalid or not authorized to access this resource.", "code": "UNAUTHORIZED"}
Handling Errors
When making API requests, you should always check the response status code and message to ensure that the request was successful. If the status code indicates an error, you should handle it appropriately based on the error message.
Handling Errors
fetch('https://api.example.com/v2/latest-headlines?country=us', { headers: { "Authorization": "Bearer YOUR_API_KEY", }, }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { // Handle the response data }) .catch(error => { // Handle any errors that occur during the request console.error('Error fetching data:', error); });
What's next
- Want to learn how to query available sources? Sources endpoint
- Want to learn how to query articles efficiently? Learn about querying