@@ -58,28 +58,33 @@ fetchData(); // Error fetching data: ....
58
58
If you have multiple asynchronous operations, you can nest ` try...catch ` blocks to handle errors at different levels.
59
59
60
60
``` js live
61
- async function fetchData () {
62
- try {
63
- // Invalid URl
64
- const response = await fetch (' https://api.example.com/data' );
65
- const data = await response .json ();
66
- console .log (data);
67
- } catch (error) {
68
- console .error (' Error fetching data:' , error);
69
- }
61
+ async function fetchUser () {
62
+ // Simulate a successful async operation
63
+ return { id: 1 , name: ' Alice' };
70
64
}
71
65
72
- async function processData () {
66
+ async function fetchUserPosts () {
67
+ // Simulate a failed async operation
68
+ throw new Error (' Failed to fetch posts' );
69
+ }
70
+
71
+ async function loadUserData () {
73
72
try {
74
- await fetchData ();
75
- // Additional processing
76
- console .log (arr); // Trying to reference an undefined variable will throw an error
77
- } catch (error) {
78
- console .error (' Error processing data:' , error);
73
+ const user = await fetchUser ();
74
+ console .log (' User:' , user);
75
+
76
+ try {
77
+ const posts = await fetchUserPosts ();
78
+ console .log (' Posts:' , posts);
79
+ } catch (postsError) {
80
+ console .error (' Error fetching posts:' , postsError .message );
81
+ }
82
+ } catch (userError) {
83
+ console .error (' Error fetching user:' , userError .message );
79
84
}
80
85
}
81
86
82
- processData ();
87
+ loadUserData ();
83
88
```
84
89
85
90
## Using ` .catch() ` with Promises
0 commit comments