Skip to content

Commit 1c4e939

Browse files
authored
Merge pull request #105 from xsteacy/master
Error handling with promises
2 parents 0be5d90 + 15636e4 commit 1c4e939

File tree

3 files changed

+57
-57
lines changed

3 files changed

+57
-57
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The answer is: **no, it won't**:
1+
La réponse est: **Non, cela n'arrivera pas:**:
22

33
```js run
44
new Promise(function(resolve, reject) {
@@ -8,6 +8,6 @@ new Promise(function(resolve, reject) {
88
}).catch(alert);
99
```
1010

11-
As said in the chapter, there's an "implicit `try..catch`" around the function code. So all synchronous errors are handled.
11+
Comme décrit dans le chapitre, il y a un "`try..catch` implicite" autour du code de la fonction. Toutes les erreurs synchrones sont donc traitées.
1212

13-
But here the error is generated not while the executor is running, but later. So the promise can't handle it.
13+
Mais ici, l'erreur n'est pas générée pendant l'exécution de l'exécuteur, mais plus tard. Donc la promesse ne peut pas tenir.

1-js/11-async/04-promise-error-handling/01-error-async/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Error in setTimeout
1+
# Erreur dans setTimeout
22

3-
What do you think? Will the `.catch` trigger? Explain your answer.
3+
Qu'en pensez-vous ? Est-ce que le `.catch` va se déclencher ? Expliquez votre réponse.
44

55
```js
66
new Promise(function(resolve, reject) {
Lines changed: 52 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11

2-
# Error handling with promises
2+
# Gestion des erreurs avec des promesses
33

4-
Promise chains are great at error handling. When a promise rejects, the control jumps to the closest rejection handler. That's very convenient in practice.
4+
Les chaînes de promesses sont excellentes pour la gestion des erreurs. Lorsqu'une promesse est rejetée, le contrôle saute au gestionnaire de rejet le plus proche. C'est très pratique en pratique.
55

6-
For instance, in the code below the URL to `fetch` is wrong (no such site) and `.catch` handles the error:
6+
Par exemple, dans le code en dessous de l'URL de `fetch` est faux (aucun site de ce type) et `.catch` gère l'erreur :
77

88
```js run
99
*!*
10-
fetch('https://no-such-server.blabla') // rejects
10+
fetch('https://no-such-server.blabla') // rejets
1111
*/!*
1212
.then(response => response.json())
13-
.catch(err => alert(err)) // TypeError: failed to fetch (the text may vary)
13+
.catch(err => alert(err)) // TypeError: failed to fetch (le texte peut varier)
1414
```
1515

16-
As you can see, the `.catch` doesn't have to be immediate. It may appear after one or maybe several `.then`.
16+
Comme vous pouvez le voir, le `.catch` n'a pas besoin d'être immédiat. Il peut apparaître après un ou peut-être plusieurs `.then`.
1717

18-
Or, maybe, everything is all right with the site, but the response is not valid JSON. The easiest way to catch all errors is to append `.catch` to the end of chain:
18+
Ou, peut-être, que tout va bien avec le site, mais la réponse JSON n'est pas valide. La façon la plus simple d'attraper toutes les erreurs est d'ajouter `.catch` à la fin de la chaîne :
1919

2020
```js run
2121
fetch('/article/promise-chaining/user.json')
@@ -38,13 +38,13 @@ fetch('/article/promise-chaining/user.json')
3838
*/!*
3939
```
4040

41-
Normally, such `.catch` doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it.
41+
Normalement, un tel `.catch` ne se déclenche pas du tout. Mais si l'une des promesses ci-dessus rejette (un problème de réseau, un json invalide ou autre), alors il l'attraperait.
4242

43-
## Implicit try..catch
43+
## try..catch implicite
4444

45-
The code of a promise executor and promise handlers has an "invisible `try..catch`" around it. If an exception happens, it gets caught and treated as a rejection.
45+
Le code d'un exécuteur de promesses et d'un gestionnaire de promesses est entouré d'un "`try...catch` invisible". Si une exception se produit, elle est prise en compte et traitée comme un rejet.
4646

47-
For instance, this code:
47+
Par exemple, ce code:
4848

4949
```js run
5050
new Promise((resolve, reject) => {
@@ -54,7 +54,7 @@ new Promise((resolve, reject) => {
5454
}).catch(alert); // Error: Whoops!
5555
```
5656

57-
...Works exactly the same as this:
57+
...Fonctionne exactement de la même façon que ceci:
5858

5959
```js run
6060
new Promise((resolve, reject) => {
@@ -64,48 +64,48 @@ new Promise((resolve, reject) => {
6464
}).catch(alert); // Error: Whoops!
6565
```
6666

67-
The "invisible `try..catch`" around the executor automatically catches the error and turns it into rejected promise.
67+
Le "`try..catch` invisible" autour de l'exécuteur attrape automatiquement l'erreur et la transforme en promesse rejetée.
6868

69-
This happens not only in the executor function, but in its handlers as well. If we `throw` inside a `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler.
69+
Cela se produit non seulement dans la fonction exécuteur, mais aussi dans ses gestionnaires. Si nous utilisons `throw` à l'intérieur d'un gestionnaire `.then', cela signifie une promesse rejetée, donc le contrôle saute au gestionnaire d'erreur le plus proche.
7070

71-
Here's an example:
71+
En voici un exemple:
7272

7373
```js run
7474
new Promise((resolve, reject) => {
7575
resolve("ok");
7676
}).then((result) => {
7777
*!*
78-
throw new Error("Whoops!"); // rejects the promise
78+
throw new Error("Whoops!"); // rejette la promesse
7979
*/!*
8080
}).catch(alert); // Error: Whoops!
8181
```
8282

83-
This happens for all errors, not just those caused by the `throw` statement. For example, a programming error:
83+
Cela se produit pour toutes les erreurs, pas seulement celles causées par l'état `throw`. Par exemple, une erreur de programmation :
8484

8585
```js run
8686
new Promise((resolve, reject) => {
8787
resolve("ok");
8888
}).then((result) => {
8989
*!*
90-
blabla(); // no such function
90+
blabla(); // aucune fonction de ce type
9191
*/!*
9292
}).catch(alert); // ReferenceError: blabla is not defined
9393
```
9494

95-
The final `.catch` not only catches explicit rejections, but also occasional errors in the handlers above.
95+
Le `.catch` final n'attrape pas seulement les rejets explicites, mais aussi les erreurs occasionnelles dans les gestionnaires ci-dessus.
9696

97-
## Rethrowing
97+
## Renouvellement
9898

99-
As we already noticed, `.catch` at the end of the chain is similar to `try..catch`. We may have as many `.then` handlers as we want, and then use a single `.catch` at the end to handle errors in all of them.
99+
Comme nous l'avons déjà remarqué, `.catch` à la fin de la chaîne est similaire à `try...catch`. Nous pouvons avoir autant de gestionnaires `.then` que nous le voulons, puis utiliser un seul `.catch` à la fin pour gérer les erreurs dans chacun d'eux.
100100

101-
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.
101+
Dans un `try...catch` régulier nous pouvons analyser l'erreur et peut-être la relancer si nous ne pouvons pas la gérer. La même chose est possible pour les promesses.
102102

103-
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.
103+
Si nous utilisons`throw` dans `.catch`, alors le contrôle passe au gestionnaire d'erreur suivant qui est plus proche. Et si nous gérons l'erreur et finissons normalement, alors elle continue jusqu'au gestionnaire `.then` le plus proche.
104104

105105
In the example below the `.catch` successfully handles the error:
106106

107107
```js run
108-
// the execution: catch -> then
108+
// l'exécution: catch -> then
109109
new Promise((resolve, reject) => {
110110

111111
throw new Error("Whoops!");
@@ -117,12 +117,12 @@ new Promise((resolve, reject) => {
117117
}).then(() => alert("Next successful handler runs"));
118118
```
119119

120-
Here the `.catch` block finishes normally. So the next successful `.then` handler is called.
120+
Ici, le bloc `.catch` se termine normalement. Le prochain gestionnaire `.then` réussi est donc appelé.
121121

122-
In the example below we see the other situation with `.catch`. The handler `(*)` catches the error and just can't handle it (e.g. it only knows how to handle `URIError`), so it throws it again:
122+
Dans l'exemple ci-dessous nous voyons l'autre situation avec `.catch`. Le gestionnaire `(*)` attrape l'erreur et ne peut tout simplement pas la gérer (par ex: il sait seulement comment gérer `URIError`), donc il la relance:
123123

124124
```js run
125-
// the execution: catch -> catch -> then
125+
// l'exécution: catch -> catch -> then
126126
new Promise((resolve, reject) => {
127127

128128
throw new Error("Whoops!");
@@ -135,51 +135,51 @@ new Promise((resolve, reject) => {
135135
alert("Can't handle such error");
136136

137137
*!*
138-
throw error; // throwing this or another error jumps to the next catch
138+
throw error; // lancer cette erreur ou une autre saute au prochain catch.
139139
*/!*
140140
}
141141

142142
}).then(function() {
143-
/* doesn't run here */
143+
/* ne s'exécute pas ici */
144144
}).catch(error => { // (**)
145145

146146
alert(`The unknown error has occurred: ${error}`);
147-
// don't return anything => execution goes the normal way
147+
// ne retourne rien => l'exécution se déroule normalement
148148

149149
});
150150
```
151151

152152
The execution jumps from the first `.catch` `(*)` to the next one `(**)` down the chain.
153153

154-
## Unhandled rejections
154+
## Rejets non traités
155155

156-
What happens when an error is not handled? For instance, we forgot to append `.catch` to the end of the chain, like here:
156+
Que se passe-t-il lorsqu'une erreur n'est pas traitée ? Par exemple, nous avons oublié d'ajouter `.catch` à la fin de la chaîne, comme ici :
157157

158158
```js untrusted run refresh
159159
new Promise(function() {
160-
noSuchFunction(); // Error here (no such function)
160+
noSuchFunction(); // Erreur ici (aucune fonction de ce type)
161161
})
162162
.then(() => {
163-
// successful promise handlers, one or more
164-
}); // without .catch at the end!
163+
// gestionnaires de promesses réussit, une ou plus
164+
}); // sans .catch à la fin!
165165
```
166166

167-
In case of an error, the promise becomes rejected, and the execution should jump to the closest rejection handler. But there is none. So the error gets "stuck". There's no code to handle it.
167+
En cas d'erreur, la promesse est rejetée et l'exécution doit passer au gestionnaire de rejet le plus proche. Mais il n'y en a pas. L'erreur est donc "coincée". Il n'y a pas de code pour le gérer.
168168

169-
In practice, just like with regular unhandled errors in code, it means that something has terribly gone wrong.
169+
En pratique, tout comme pour les erreurs régulières qui sont non gérées dans le code, cela signifie que quelque chose a très mal tourné.
170170

171-
What happens when a regular error occurs and is not caught by `try..catch`? The script dies with a message in console. Similar thing happens with unhandled promise rejections.
171+
Que se passe-t-il lorsqu'une erreur régulière se produit et n'est pas détectée par `try...catch` ? Le script meurt avec un message dans la console. Il se produit la même chose lors du rejet de promesses non tenues.
172172

173-
JavaScript engine tracks such rejections and generates a global error in that case. You can see it in the console if you run the example above.
173+
Le moteur JavaScript suit ces rejets et génère une erreur globale dans ce cas. Vous pouvez le voir dans la console si vous exécutez l'exemple ci-dessus.
174174

175-
In the browser we can catch such errors using the event `unhandledrejection`:
175+
Dans le navigateur, nous pouvons détecter de telles erreurs en utilisant l'événement `unhandledrejection`:
176176

177177
```js run
178178
*!*
179179
window.addEventListener('unhandledrejection', function(event) {
180-
// the event object has two special properties:
181-
alert(event.promise); // [object Promise] - the promise that generated the error
182-
alert(event.reason); // Error: Whoops! - the unhandled error object
180+
// l'objet event possède deux propriétés spéciales:
181+
alert(event.promise); // [object Promise] - la promesse qui a généré l'erreur
182+
alert(event.reason); // Error: Whoops! - l'objet d'erreur non géré
183183
});
184184
*/!*
185185

@@ -188,17 +188,17 @@ new Promise(function() {
188188
}); // no catch to handle the error
189189
```
190190

191-
The event is the part of the [HTML standard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections).
191+
L'événement fait partie des [standards HTML](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections) *(en anglais)*.
192192

193-
If an error occurs, and there's no `.catch`, the `unhandledrejection` handler triggers, and gets the `event` object with the information about the error, so we can do something.
193+
Si une erreur se produit, et qu'il n'y a pas de `.catch`, le gestionnaire `unhandledrejection` se déclenche, et reçoit l'objet `event` avec les informations sur l'erreur, donc nous pouvons faire quelque chose.
194194

195-
Usually such errors are unrecoverable, so our best way out is to inform the user about the problem and probably report the incident to the server.
195+
Habituellement, de telles erreurs sont irrécupérables, donc notre meilleure solution est d'informer l'utilisateur à propos du problème et probablement de signaler l'incident au serveur.
196196

197-
In non-browser environments like Node.js there are other ways to track unhandled errors.
197+
Dans les environnements sans navigateur comme Node.js, il existe d'autres moyens de suivre les erreurs non gérées.
198198

199-
## Summary
199+
## Résumé
200200

201-
- `.catch` handles errors in promises of all kinds: be it a `reject()` call, or an error thrown in a handler.
202-
- We should place `.catch` exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and rethrow unknown ones (maybe they are programming mistakes).
203-
- It's ok not to use `.catch` at all, if there's no way to recover from an error.
204-
- In any case we should have the `unhandledrejection` event handler (for browsers, and analogs for other environments), to track unhandled errors and inform the user (and probably our server) about the them, so that our app never "just dies".
201+
- `.catch` gère les erreurs dans les promesses de toutes sortes : qu'il s'agisse d'un appel `reject()', ou d'une erreur lancée dans un gestionnaire.
202+
- Nous devrions placer `.catch' exactement aux endroits où nous voulons traiter les erreurs et savoir comment les traiter. Le gestionnaire doit analyser les erreurs (les classes d'erreurs personnalisées aident) et relancer les erreurs inconnues (ce sont peut-être des erreurs de programmation).
203+
- C'est acceptable de ne pas utiliser `.catch` du tout, s'il n'y a aucun moyen de récupérer d'une erreur.
204+
- Dans tous les cas, nous devrions avoir le gestionnaire d'événements `unhandledrejection` (pour les navigateurs, et les analogues pour les autres environnements), pour suivre les erreurs non gérées et informer l'utilisateur (et probablement notre serveur) à leur sujet, afin que notre application ne "meurt jamais".

0 commit comments

Comments
 (0)