javascript / intermediate
Snippet
Managing Network Failures in React Handlers with Custom Error Instances
Custom error classes extending the built-in Error object allow React components to categorize runtime failures distinctly. By inspecting errors with the `instanceof` operator in the catch block, components can set specific error states and render tailored UI alerts rather than displaying opaque messages.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class ApiTimeoutError extends Error {constructor(message = 'Request timed out') {super(message);this.name = 'ApiTimeoutError';}}function UserProfileViewer({ userId }) {const [userData, setUserData] = React.useState(null);const [errorType, setErrorType] = React.useState(null);const handleFetchProfile = async () => {setErrorType(null);try {const response = await fetch(`/api/users/${userId}`);if (!response.ok) {throw new ApiTimeoutError('Failed to retrieve user profile.');}const data = await response.json();setUserData(data);} catch (err) {if (err instanceof ApiTimeoutError) {setErrorType('timeout');} else {setErrorType('generic');}}};return (<div><button onClick={handleFetchProfile}>Load Profile</button>{errorType === 'timeout' && <p role="alert">Timeout: Server took too long.</p>}{errorType === 'generic' && <p role="alert">Unexpected network error occurred.</p>}{userData && <div>Welcome, {userData.name}</div>}</div>);}
react
Breakdown
1
class ApiTimeoutError extends Error {
Defines a custom error class inheriting standard Error prototype behavior and stack traces.
2
if (err instanceof ApiTimeoutError) {
Distinguishes specific business or transport failure types from unexpected JavaScript exceptions.
3
{errorType === 'timeout' && <p role="alert">Timeout: Server took too long.</p>}
Conditionally displays an accessible alert message mapped directly to the verified error category.