You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> **Note :** As you can see, *try / catch* are necessary to handle errors. But if you are making *express routes*, you can use a middleware to avoid error handling and have a very pleasant code to read. See [this article from Alex Bazhenov](https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016) to learn more.
1356
+
##### Error handling
1357
+
1358
+
Unless we add *try / catch* blocks around *await* expressions, uncaught exceptions – regardless of whether they were raised in the body of your *async* function or while it’s suspended during *await* – will reject the promise returned by the *async* function. [(Ref: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).
1359
+
1360
+
With promises, here is how you would handle the error chain:
1361
+
1362
+
```js
1363
+
functiongetUser() => { // This promise will be rejected!
1364
+
returnnewPromise((res, rej) =>rej("User not found !")
1365
+
};
1366
+
1367
+
functiongetAvatarByUsername(userId) {
1368
+
returnnewPromise((res, rej) =>
1369
+
getUser(userId)
1370
+
.then(user=>res(user.avatar))
1371
+
.catch(err=>rej(err))
1372
+
);
1373
+
}
1374
+
1375
+
functiongetUserAvatar(username) {
1376
+
returnnewPromise((res, rej) =>
1377
+
getAvatarByUsername(username)
1378
+
.then(avatar=>res({ username, avatar }))
1379
+
.catch(err=>rej(err))
1380
+
);
1381
+
}
1382
+
1383
+
getUserAvatar('mbeaudru')
1384
+
.then(res=>console.log(res))
1385
+
.catch(err=>console.log(err)); // "User not found !"
1386
+
```
1387
+
1388
+
If you forgot a *catch*, the error will be uncaught!
1389
+
1390
+
But with *async* functions, if an error is thrown in it's body the promise will reject:
1391
+
1392
+
```js
1393
+
functiongetUser() => { // This promise will be rejected!
1394
+
returnnewPromise((res, rej) =>rej("User not found !")
1395
+
};
1396
+
1397
+
asyncfunctiongetAvatarByUsername(userId) => {
1398
+
constuser=awaitgetUser(userId);
1399
+
returnuser.avatar;
1400
+
};
1401
+
1402
+
asyncfunctiongetUserAvatar(username) {
1403
+
var avatar =awaitgetAvatarByUsername(username);
1404
+
return { username, avatar };
1405
+
}
1406
+
1407
+
getUserAvatar('mbeaudru')
1408
+
.then(res=>console.log(res))
1409
+
.catch(err=>console.log(err)); // "User not found !"
0 commit comments