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
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.
5
5
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 :
7
7
8
8
```js run
9
9
*!*
10
-
fetch('https://no-such-server.blabla') //rejects
10
+
fetch('https://no-such-server.blabla') //rejets
11
11
*/!*
12
12
.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)
14
14
```
15
15
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`.
17
17
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 :
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.
42
42
43
-
## Implicit try..catch
43
+
## try..catch implicite
44
44
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.
46
46
47
-
For instance, this code:
47
+
Par exemple, ce code:
48
48
49
49
```js run
50
50
newPromise((resolve, reject) => {
@@ -54,7 +54,7 @@ new Promise((resolve, reject) => {
54
54
}).catch(alert); // Error: Whoops!
55
55
```
56
56
57
-
...Works exactly the same as this:
57
+
...Fonctionne exactement de la même façon que ceci:
58
58
59
59
```js run
60
60
newPromise((resolve, reject) => {
@@ -64,48 +64,48 @@ new Promise((resolve, reject) => {
64
64
}).catch(alert); // Error: Whoops!
65
65
```
66
66
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.
68
68
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.
70
70
71
-
Here's an example:
71
+
En voici un exemple:
72
72
73
73
```js run
74
74
newPromise((resolve, reject) => {
75
75
resolve("ok");
76
76
}).then((result) => {
77
77
*!*
78
-
thrownewError("Whoops!"); //rejects the promise
78
+
thrownewError("Whoops!"); //rejette la promesse
79
79
*/!*
80
80
}).catch(alert); // Error: Whoops!
81
81
```
82
82
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 :
84
84
85
85
```js run
86
86
newPromise((resolve, reject) => {
87
87
resolve("ok");
88
88
}).then((result) => {
89
89
*!*
90
-
blabla(); //no such function
90
+
blabla(); //aucune fonction de ce type
91
91
*/!*
92
92
}).catch(alert); // ReferenceError: blabla is not defined
93
93
```
94
94
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.
96
96
97
-
## Rethrowing
97
+
## Renouvellement
98
98
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.
100
100
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.
102
102
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.
104
104
105
105
In the example below the `.catch` successfully handles the error:
106
106
107
107
```js run
108
-
//the execution: catch -> then
108
+
//l'exécution: catch -> then
109
109
newPromise((resolve, reject) => {
110
110
111
111
thrownewError("Whoops!");
@@ -117,12 +117,12 @@ new Promise((resolve, reject) => {
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é.
121
121
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:
123
123
124
124
```js run
125
-
//the execution: catch -> catch -> then
125
+
//l'exécution: catch -> catch -> then
126
126
newPromise((resolve, reject) => {
127
127
128
128
thrownewError("Whoops!");
@@ -135,51 +135,51 @@ new Promise((resolve, reject) => {
135
135
alert("Can't handle such error");
136
136
137
137
*!*
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.
139
139
*/!*
140
140
}
141
141
142
142
}).then(function() {
143
-
/*doesn't run here*/
143
+
/*ne s'exécute pas ici*/
144
144
}).catch(error=> { // (**)
145
145
146
146
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
148
148
149
149
});
150
150
```
151
151
152
152
The execution jumps from the first `.catch``(*)` to the next one `(**)` down the chain.
153
153
154
-
## Unhandled rejections
154
+
## Rejets non traités
155
155
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 :
157
157
158
158
```js untrusted run refresh
159
159
newPromise(function() {
160
-
noSuchFunction(); //Error here (no such function)
160
+
noSuchFunction(); //Erreur ici (aucune fonction de ce type)
161
161
})
162
162
.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!
165
165
```
166
166
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.
168
168
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é.
170
170
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.
172
172
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.
174
174
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`:
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é
183
183
});
184
184
*/!*
185
185
@@ -188,17 +188,17 @@ new Promise(function() {
188
188
}); // no catch to handle the error
189
189
```
190
190
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)*.
192
192
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.
194
194
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.
196
196
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.
198
198
199
-
## Summary
199
+
## Résumé
200
200
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