javascript / beginner
Snippet
Handling Asynchronous Action Errors with Try-Catch
Handling errors during asynchronous operations keeps React applications stable. Wrapping an await call inside a try-catch block captures thrown exceptions and stores error messages in component state for user display.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { useState } from 'react';export function SaveForm() {const [errorMessage, setErrorMessage] = useState(null);const handleSave = async () => {try {setErrorMessage(null);await Promise.reject(new Error('Network request failed'));} catch (err) {setErrorMessage(err.message);}};return (<div><button onClick={handleSave}>Save</button>{errorMessage && <p role="alert">{errorMessage}</p>}</div>);}
react
Breakdown
1
try { setErrorMessage(null); ... }
Clears any existing error messages before executing the asynchronous operation.
2
catch (err) { setErrorMessage(err.message); }
Catches any thrown exception and stores its message in state to alert the user.