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
Now it works. But there's a potential problem in the code.
253
+
The code works. But there's a potential problem in it.
254
254
255
255
Look at the line `(*)`: how can we do something *after* the avatar is removed? For instance, we'd like to show a form for editing that user or something else.
An async action should always return a promise. That makes possible to plan actions after it.
283
+
Now when `setTimeout` runs the function, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data.
284
+
285
+
As a rule, an asynchronous action should always return a promise. That makes possible to plan actions after it. Even if we don't plan to extend the chain now, we may need it later.
284
286
285
-
Finally, we can split it into reusable functions:
287
+
Finally, we can split the code into reusable functions:
Now when `setTimeout` runs the function, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data.
321
+
## Error handling
322
+
323
+
Asynchronous actions may sometimes fail: in case of an error the corresponding promises becomes rejected. For instance, `fetch` fails if the remote server is not available. We can use `.catch` to handle errors (rejections).
324
+
325
+
Promise chaining is great at that aspect. When a promise rejects, the control jumps to the closest rejection handler down the chain. That's very convenient in practice.
326
+
327
+
For instance, in the code below the URL is wrong (no such server) and `.catch` handles the error:
328
+
329
+
```js run
330
+
*!*
331
+
fetch('https://no-such-server.blabla') // rejects
332
+
*/!*
333
+
.then(response=>response.json())
334
+
.catch(err=>alert(err)) // TypeError: failed to fetch (the text may vary)
335
+
```
336
+
337
+
Or, maybe, everything is all right with the server, but the response is not a valid JSON:
338
+
339
+
```js run
340
+
fetch('/') // fetch works fine now, the server responds successfully
341
+
*!*
342
+
.then(response=>response.json()) // rejects: the page is HTML, not a valid json
343
+
*/!*
344
+
.catch(err=>alert(err)) // SyntaxError: Unexpected token < in JSON at position 0
345
+
```
346
+
347
+
348
+
In the example below we append `.catch` to handle all errors in the avatar-loading-and-showing chain:
Here `.catch` doesn't trigger at all, because there are no errors. But if any of the promises above rejects, then it would execute.
370
+
371
+
## Implicit try..catch
372
+
373
+
The code of the executor and promise handlers has an "invisible `try..catch`" around it. If an error happens, it gets caught and treated as a rejection.
374
+
375
+
For instance, this code:
376
+
377
+
```js run
378
+
newPromise(function(resolve, reject) {
379
+
*!*
380
+
thrownewError("Whoops!");
381
+
*/!*
382
+
}).catch(alert); // Error: Whoops!
383
+
```
384
+
385
+
...Works the same way as this:
386
+
387
+
```js run
388
+
newPromise(function(resolve, reject) {
389
+
*!*
390
+
reject(newError("Whoops!"));
391
+
*/!*
392
+
}).catch(alert); // Error: Whoops!
393
+
```
394
+
395
+
The "invisible `try..catch`" around the executor automatically catches the error and treats it as a rejection.
396
+
397
+
That's so not only in the executor, but in handlers as well. If we `throw` inside `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler.
398
+
399
+
Here's an example:
400
+
401
+
```js run
402
+
newPromise(function(resolve, reject) {
403
+
resolve("ok");
404
+
}).then(function(result) {
405
+
*!*
406
+
thrownewError("Whoops!"); // rejects the promise
407
+
*/!*
408
+
}).catch(alert); // Error: Whoops!
409
+
```
410
+
411
+
That's so not only for `throw`, but for any errors, including programming errors as well:
412
+
413
+
```js run
414
+
newPromise(function(resolve, reject) {
415
+
resolve("ok");
416
+
}).then(function(result) {
417
+
*!*
418
+
blabla(); // no such function
419
+
*/!*
420
+
}).catch(alert); // ReferenceError: blabla is not defined
421
+
```
422
+
423
+
As a side effect, the final `.catch` not only catches explicit rejections, but also occasional errors in the handlers above.
424
+
425
+
## Rethrowing
426
+
427
+
As we already noticed, `.catch` behaves like `try..catch`. We may have as many `.then` as we want, and then use a single `.catch` at the end to handle errors in all of them.
428
+
429
+
In a regular `try..catch` we can analyze the error and maybe rethrow it if can't handle. The same thing is possible for promises. If we `throw` inside `.catch`, then the control goes to the next closest error handler. And if we handle the error and finish normally, then it continues to the closest successful `.then` handler.
430
+
431
+
In the example below the `.catch` successfully handles the error:
Here the `.catch` block finishes normally. So the next successful handler is called. Or it could return something, that would be the same.
446
+
447
+
...And here the `.catch` block analyzes the error and throws it again:
448
+
449
+
```js run
450
+
// the execution: catch -> catch -> then
451
+
newPromise(function(resolve, reject) {
452
+
453
+
thrownewError("Whoops!");
454
+
455
+
}).catch(function(error) { // (*)
456
+
457
+
if (error instanceofURIError) {
458
+
// handle it
459
+
} else {
460
+
alert("Can't handle such error");
461
+
462
+
*!*
463
+
throw error; // throwing this or another error jumps to the next catch
464
+
*/!*
465
+
}
466
+
467
+
}).then(function() {
468
+
/* never runs here */
469
+
}).catch(error=> { // (**)
470
+
471
+
alert(`The unknown error has occured: ${error}`);
472
+
// don't return anything => execution goes the normal way
473
+
474
+
});
475
+
```
476
+
477
+
The handler `(*)` catches the error and just can't handle it, because it's not `URIError`, so it throws it again. Then the execution jumps to the next `.catch` down the chain `(**)`.
478
+
479
+
## Unhandled rejections
480
+
481
+
...But what if we forget to append an error handler to the end of the chain?
482
+
483
+
Like here:
484
+
485
+
```js untrusted run refresh
486
+
newPromise(function() {
487
+
errorHappened(); // Error here (no such function)
488
+
});
489
+
```
490
+
491
+
Or here:
492
+
493
+
```js untrusted run refresh
494
+
newPromise(function() {
495
+
thrownewError("Whoops!");
496
+
}).then(function() {
497
+
// ...something...
498
+
}).then(function() {
499
+
// ...something else...
500
+
}).then(function() {
501
+
// ...but no catch after it!
502
+
});
503
+
```
504
+
505
+
Technically, when an error happens, the promise state becomes "rejected", and the execution should jump to the closest rejection handler. But there is no such handler in the examples above.
506
+
507
+
Usually that means that the code is bad. Indeed, how come that there's no error handling?
508
+
509
+
Most JavaScript engines track such situations and generate a global error in that case. In the browser we can catch it using `window.addEventListener('unhandledrejection')` as specified in the [HTML standard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections):
alert(event.promise); // [object Promise] - the promise that generated the error
516
+
alert(event.reason); // Error: Whoops! - the unhandled error object
517
+
});
518
+
519
+
newPromise(function() {
520
+
thrownewError("Whoops!");
521
+
}).then(function() {
522
+
// ...something...
523
+
}).then(function() {
524
+
// ...something else...
525
+
}).then(function() {
526
+
// ...but no catch after it!
527
+
});
528
+
```
529
+
530
+
Now if an error has occured, and there's no `.catch`, the event `unhandledrejection` triggers, and our handler can do something with the exception. Once again, such situation is usually a programming error.
531
+
532
+
In non-browser environments like Node.JS there are other similar ways to track unhandled errors.
533
+
534
+
## Summary
535
+
536
+
To summarize, `.then/catch(handler)` returns a new promise that changes depending on what handler does:
537
+
538
+
1. If it returns a value or finishes without a `return` (same as `return undefined`), then the new promise becomes resolved, and the closest resolve handler (the first argument of `.then`) is called with that value.
539
+
2. If it throws an error, then the new promise becomes rejected, and the closest rejection handler (second argument of `.then` or `.catch`) is called with it.
540
+
3. If it returns a promise, then JavaScript waits until it settles and then acts on its outcome the same way.
541
+
542
+
The picture of how the promise returned by `.then/catch` changes:
543
+
544
+

545
+
546
+
The smaller picture of how handlers are called:
547
+
548
+

549
+
550
+
In the examples of error handling above the `.catch` was always the last in the chain. In practice though, not every promise chain has a `.catch`. Just like regular code is not always wrapped in `try..catch`.
551
+
552
+
We should place `.catch` exactly in the places where we want to handle errors and know how to handle them.
320
553
321
-
Here we assumed that everything works as intended. But that's not always the case. In the next chapter we'll talk about error handling.
554
+
For errors that are outside of that scope we should have the `unhandledrejection` event handler. Such unknown errors are usually unrecoverable, so all we should do is to inform the user and probably report to our server about the incident.
0 commit comments