How to Handle Errors in Fetch API Calls with Try-Catch Block
To handle errors in fetch API calls, you can use a try-catch block. This block allows you to catch and manage any errors that occur during the process.
try {
const response = await fetch(
'https://free-api.cveoy.top/v2/completions',
{
method: 'POST',
body: JSON.stringify({
prompt: query,
}),
headers: {
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// handle the response data
} catch (error) {
// handle the error
console.log(error.message);
}
Explanation:
tryBlock: The code within this block is executed as usual. If an error occurs, the execution is immediately stopped and control is passed to thecatchblock.fetchCall: This is where the API request is made. Make sure to replace 'https://free-api.cveoy.top/v2/completions' with your actual API endpoint.response.ok: This checks if the response status is within the 200-299 range (indicating success). If not, an error is thrown.throw new Error(...): This explicitly throws an error with a message describing the problem (e.g., 'HTTP error! status: 404').catchBlock: This block catches any errors thrown within thetryblock. It receives the error object as an argument (error).
How to Handle Errors:
- Logging: Use
console.log(error.message)to display the error message in the console. This is helpful for debugging. - User Feedback: You can provide feedback to the user about the error. For instance, display a message like 'Something went wrong, please try again later.'
- Retry Mechanism: Consider implementing a retry mechanism where you retry the fetch call after a certain delay if an error occurs. This can help handle temporary network issues.
By using a try-catch block, you can ensure your code gracefully handles errors and continues to function properly even in unexpected situations. Remember to adapt the error handling logic based on your specific application requirements.
原文地址: https://www.cveoy.top/t/topic/mlIm 著作权归作者所有。请勿转载和采集!