1. Introduction
In modern web development, the Fetch API is one of the main tools used to perform network requests. It provides a concise syntax based on Promise, making asynchronous operations more intuitive and manageable. However, in actual use, developers often encounter HTTP status code errors, such as 404 error, that is, "not found" error. This error usually indicates that the requested resource does not exist on the server or the path is wrong. Understanding how to properly handle 404 errors is essential for building robust and user-friendly applications.
This article will explore in detail the causes of obtaining 404 errors when using the Fetch API, how to detect and deal with these errors, and best practices to help developers effectively deal with and resolve such problems.
2. Understanding HTTP 404 errors
2.1 What is a 404 error?
404 Error, full nameHTTP 404 Not Found,yesHTTPOne of the common status codes in the protocol。 It means that the client can communicate with the server, but the server cannot find the resource requested by the client. This usually occurs in the following situations:
- The requested URL path is wrong.
- The resource has been deleted or moved.
- The server is configured incorrectly, resulting in the resource being inaccessible.
2.2 The impact of 404 errors
When a client receives a 404 error, it usually means the following things:
- Loss of user experience: Users are unable to access what they expect, which can lead to frustration or abandonment of the use of the app.
- SEO impact: Search engines regard 404 error pages as negative signals, which may affect the search ranking of the website.
- Function interruption: If the 404 error occurs at a critical function point, the application function may not function properly.
3. How does the Fetch API handle HTTP errors
3.1 Basic working principle of the Fetch API
Fetch API
Used to perform network requests, return aPromise, the Promise is resolved or rejected when the request succeeds or fails. The key point is:
-
Network error: For example, if you cannot connect to the server, Fetch Promise will be denied (
rejected
)。 -
HTTP Error Status Code: For example, 404, 500, etc., Fetch Promise will still besolve(
fulfilled
), but respond to the object'sok
The attribute isfalse
,andstatus
The attribute contains a specific status code.
3.2 Fetch API and HTTP status code
When using the Fetch API to make a request, Fetch Promise will be resolved without being rejected even if the server returns a 404 error. This means you need to manually check the status code of the response object to determine if the request is successful.
Example:
fetch('/nonexistent-endpoint') .then(response => { if (!) { throw new Error(`HTTP mistake! state: ${}`); } return (); }) .then(data => { ('data:', data); }) .catch(error => { ('An error occurred:', error); });
In the above example, even if the request returns a 404 error,catch
The block will still catch the error becausethen
An error was thrown manually in the block.
4. How to detect and handle 404 errors
4.1 Use the ok and status attributes of the response object
The response object contains multiple properties, whereok
is a Boolean value indicating whether the response status code is within the range of 200-299.status
It contains the specific HTTP status code.
Example:
fetch('/data') .then(response => { if () { return (); } else if ( === 404) { throw new Error('Resource not found (404)'); } else { throw new Error(`Server Error! state: ${}`); } }) .then(data => { ('data:', data); }) .catch(error => { ('An error occurred:', ); // Perform the corresponding operation according to the error type, such as displaying an error message to the user });
4.2 Using async/await syntax
useasync/await
It can make asynchronous code more readable and easier to handle errors.
Example:
async function fetchData(url) { try { const response = await fetch(url); if () { const data = await (); ('data:', data); return data; } else if ( === 404) { ('Resource not found (404)'); // Here you can handle 404 errors, such as displaying a specific message or redirecting } else { throw new Error(`Server Error! state: ${}`); } } catch (error) { ('An error occurred:', ); // Handle network errors or other unexpected errors } } fetchData('/nonexistent-endpoint');
4.3 Handle the error message returned by the API
Some APIs provide detailed error information in the response body when returning an error. You can parse this information to provide more specific error feedback.
Example:
async function fetchData(url) { try { const response = await fetch(url); const data = await (); // Assume that the API also returns JSON when errors if () { ('data:', data); return data; } else { // Assume that the error message is in throw new Error(`mistake: ${}`); } } catch (error) { ('An error occurred:', ); // Perform the corresponding operation according to the error type } } fetchData('/nonexistent-endpoint');
5. Best Practices
5.1 Always check the response status code
Whether it is usedthen
Chain orasync/await
, always check the responseok
Properties andstatus
code to ensure that the request is successful before processing the data.
Example:
fetch('/data') .then(response => { if (!) { throw new Error(`HTTP mistake! state: ${}`); } return (); }) .then(data => { // Process data }) .catch(error => { // Handle errors });
5.2 Provide user-friendly error feedback
When a 404 error occurs, explicit feedback is provided to the user, informing them that the requested content is not found, and may provide the option to return to the home page or search.
Example:
async function fetchData(url) { try { const response = await fetch(url); if () { const data = await (); return data; } else if ( === 404) { displayErrorMessage('The page you requested was not found. '); } else { throw new Error(`Server Error! state: ${}`); } } catch (error) { displayErrorMessage('An error occurred, please try again later. '); ('An error occurred:', error); } } function displayErrorMessage(message) { const errorDiv = ('error'); if (errorDiv) { = message; = 'block'; } }
5.3 Use the retry mechanism
For some temporary problems, such as network fluctuations, an automatic retry mechanism can be implemented to try to initiate a request again.
Example:
async function fetchWithRetry(url, options = {}, retries = 3, backoff = 300) { try { const response = await fetch(url, options); if () { return await (); } else if ( === 404) { throw new Error('Resource not found (404)'); } else { throw new Error(`Server Error! state: ${}`); } } catch (error) { if (retries > 0 && !== 'Resource not found (404)') { (`Request failed,Trying again... Number of remaining times: ${retries}`); await new Promise(resolve => setTimeout(resolve, backoff)); return fetchWithRetry(url, options, retries - 1, backoff * 2); // Exponential backoff } else { throw error; } } } fetchWithRetry('/data') .then(data => { ('data:', data); }) .catch(error => { ('The request failed in the end:', ); });
5.4 Type Checking with TypeScript
Use TypeScript to capture potential errors during the compilation phase and reduce the occurrence of runtime errors.
Example:
interface User { name: string; age: number; } async function fetchUser(url: string): Promise<User> { const response = await fetch(url); if (!) { if ( === 404) { throw new Error('User not found (404)'); } throw new Error(`Server Error! state: ${}`); } const data: User = await (); return data; } fetchUser('/users/1') .then(user => { ('user:', ); }) .catch(error => { ('An error occurred:', ); });
5.5 Recording and monitoring errors
In production environments, use error monitoring tools (such as Sentry, LogRocket) to record and monitor errors to help quickly locate and fix problems.
Example:
import * as Sentry from '@sentry/browser'; ({ dsn: 'YOUR_SENTRY_DSN' }); async function fetchData(url) { try { const response = await fetch(url); if (!) { throw new Error(`HTTP mistake! state: ${}`); } const data = await (); return data; } catch (error) { (error); ('An error occurred:', ); throw error; } } fetchData('/data') .then(data => { // Process data }) .catch(error => { // Handle errors });
6. Practical cases
6.1 Simple Fetch request handling 404 error
Scene:
Initiate a GET request to obtain user data. If the user does not exist, the server returns a 404 error. This error needs to be caught and handled on the front end.
Code example:
async function getUser(userId) { try { const response = await fetch(`/users/${userId}`); if () { const user = await (); ('User Data:', user); return user; } else if ( === 404) { ('User not found (404)'); // Can display user-friendly error messages or perform other processing } else { throw new Error(`Server Error! state: ${}`); } } catch (error) { ('Network error or other issues:', error); // Can display global error messages or retry logic } } getUser(12345);
explain:
-
Response check:use
Determine whether the request is successful.
- Specific status code processing: Handle 404 errors separately to provide specific feedback.
- General error handling: Handle other HTTP errors and network errors.
6.2 Handling 404 errors in React component
Scene:
In a React component, initiate a Fetch request to get the content of the article. If the article does not exist (return 404), a message with "Article not found" needs to be displayed.
Code example:
import React, { useEffect, useState } from 'react'; function Article({ articleId }) { const [article, setArticle] = useState(null); const [error, setError] = useState(''); useEffect(() => { async function fetchArticle() { try { const response = await fetch(`/articles/${articleId}`); if () { const data = await (); setArticle(data); } else if ( === 404) { setError('Sorry, the article you requested was not found. '); } else { throw new Error(`Server Error! state: ${}`); } } catch (err) { setError('Network error, please try again later. '); ('An error occurred:', err); } } fetchArticle(); }, [articleId]); if (error) { return <div className="error">{error}</div>; } if (!article) { return <div>loading...</div>; } return ( <div className="article"> <h1>{}</h1> <p>{}</p> </div> ); } export default Article;
explain:
-
Status Management:use
useState
Manage article data and error messages. -
Asynchronous request:exist
useEffect
initiate a Fetch request. - Error handling: Set error information according to the response status code to provide user-friendly feedback.
- Conditional Rendering: Display loading, error messages or article content according to status.
6.3 The retry mechanism deals with occasional 404 errors
Scene:
In some cases, the server may temporarily fail to find the resource (such as due to cache updates or deployment delays), and can implement a retry mechanism to try to request again.
Code example:
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) { try { const response = await fetch(url, options); if () { return await (); } else if ( === 404) { if (retries > 0) { (`Resource not found (404),Trying again... Number of remaining times: ${retries}`); await new Promise(res => setTimeout(res, delay)); return fetchWithRetry(url, options, retries - 1, delay * 2); // Exponential backoff } else { throw new Error('Resource not found (404)'); } } else { throw new Error(`Server Error! state: ${}`); } } catch (error) { if (retries > 0 && !== 'Resource not found (404)') { (`Request failed,Trying again... Number of remaining times: ${retries}`); await new Promise(res => setTimeout(res, delay)); return fetchWithRetry(url, options, retries - 1, delay * 2); } else { throw error; } } } fetchWithRetry('/data') .then(data => { ('data:', data); }) .catch(error => { ('The request failed in the end:', ); });
explain:
- Recursively try: When the function encounters a 404 error, decide whether to try again based on the remaining number of times.
- Exponential backoff:Double the delay time of each retry to avoid excessively frequent requests.
- Error terminated: After the number of retrys is exhausted, an error is thrown for the caller to handle it.
Notes:
- Reasonable retry times: Avoid unlimited retry, usually set a maximum number of retry times.
- Delay policy: Combined with the index backoff strategy to avoid network congestion and server pressure.
- Specific error handling: Special processing is performed for specific error status codes (such as 404) to avoid meaningless retry.
7. Summary
In useFetch API
Proper handling of HTTP 404 errors is key to ensuring application stability and user experience when making network requests. Developers can effectively detect and respond to 404 errors through the following key measures:
-
Check the response status code: Always check the response object's
ok
Properties andstatus
code to ensure that the request is successful before processing the data. - Provide user-friendly feedback: When a 404 error occurs, the user is shown clear error information and feasible follow-up actions are provided, such as returning to the home page or re-search.
- Implement the retry mechanism: For occasional 404 errors, a retry strategy can be implemented to increase the possibility of successful requests.
-
use
async/await
andtry/catch
: Take advantage of modern JavaScript features to simplify asynchronous code and error handling logic. - TypeScript for type checking: Through static type checking, potential errors can be discovered in advance to reduce the occurrence of runtime errors.
- Record and monitor errors: In production environments, use error monitoring tools to record and analyze errors to help quickly locate and fix problems.
- Optimize API design: Ensure that the backend API returns explicit error messages when the resource does not exist and provides a useful error description.
The above is the detailed content of the solution to obtain 404 errors when using the Fetch API. For more information about obtaining 404 errors by the Fetch API, please follow my other related articles!