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
+
Las promesas encadenadas son excelentes manejando los errores. Cuando una promesa es rechazada, el control salta al manejador de rechazos más cercano. Esto es muy conveniente en la práctica.
5
5
6
-
For instance, in the code below the URL to `fetch`is wrong (no such site) and `.catch`handles the error:
6
+
Por ejemplo, en el código de abajo, la URL a la cual se le hace `fetch`es incorrecta (no existe el sitio) y al ser rechazada`.catch`maneja el error:
.catch(err=>alert(err)) // TypeError: failed to fetch (the text may vary)
13
+
.catch(err=>alert(err)) // TypeError: failed to fetch (El texto puede variar, dependiendo del error)
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
+
Como puedes ver, el`.catch`no tiene que escribirse inmediatamente después de la promesa. Este puede aparecer después de uno o quizás varios`.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
+
O, puede ocurrir, que todo en el sitio se encuentre bien, pero la respuesta no es un JSON válido. La forma más fácil de detectar todos los errores es agregando `.catch`al final de la cadena de promesas:
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
+
Lo normal es que tal `.catch`no se dispare en absoluto. Pero si alguna de las promesas anteriores es rechazada (por un error de red, un JSON inválido or cualquier otra razón), entonces el error es capturado.
42
42
43
-
## Implicit try..catch
43
+
## try..catch implícito
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
+
El código de un ejecutor de promesas y de manejadores de promesas tiene embebido un "`try..catch` invisible". Si ocurre una excepción, esta es atrapada y es tratada como un rechazo.
46
46
47
-
For instance, this code:
47
+
Por ejemplo, este código:
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
+
...Hace exactamente lo mismo que este:
58
58
59
59
```js run
60
60
newPromise((resolve, reject) => {
@@ -64,141 +64,141 @@ 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
+
El "`try..catch` invisible" embebido en el ejecutor detecta automáticamente el error y lo convierte en una promesa rechazada.
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
+
Esto sucede no solo en la función ejecutora, sino también en sus manejadores. Si hacemos`throw`dentro de una llamada a `.then`, esto devolverá una promesa rechazada, por lo que el control salta al manejador de errores más cercano.
70
70
71
-
Here's an example:
71
+
Por ejemplo:
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!"); //rechaza la promesa
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
+
Esto sucede con todos los errores, no solo los causados por la sentencia de excepción `throw`. Por ejemplo, un error de programación:
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(); //Función inexistente
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 accidental errors in the handlers above.
95
+
El `.catch`del final no solo detecta rechazos explícitos, sino también los errores accidentales en los manejadores anteriores.
96
96
97
-
## Rethrowing
97
+
## Rethrowing (relanzamiento de errores)
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
+
Como ya vimos, el `.catch`del final es similar a`try..catch`. Podemos tener tantos manejadores `.then`como queramos, y luego usar un solo`.catch`al final para manejar los errores en todos ellos.
100
100
101
-
In a regular `try..catch`we can analyze the error and maybe rethrow it if it can't be handled. The same thing is possible for promises.
101
+
En un `try..catch`normal, podemos analizar el error y quizá volver a lanzarlo si no se puede manejar. Lo mismo podemos hacer con las promesas.
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 next closest successful `.then`handler.
103
+
Si hacemos`throw`dentro de `.catch`, el control pasa a otro manejador de errores más cercano. Y, si manejamos el error y terminamos de forma correcta, entonces se continúa con el siguiente manejador `.then`existoso.
104
104
105
-
In the example below the `.catch`successfully handles the error:
105
+
En el ejemplo de abajo, el `.catch`maneja el error de forma exitosa:
106
106
107
107
```js run
108
-
//the execution: catch -> then
108
+
//Ejecución: catch -> then
109
109
newPromise((resolve, reject) => {
110
110
111
111
thrownewError("Whoops!");
112
112
113
113
}).catch(function(error) {
114
114
115
-
alert("The error is handled, continue normally");
115
+
alert("Error manejado, se continuará con la ejecución del código");
}).then(() =>alert("El siguiente manejador exitoso se ejecuta"));
118
118
```
119
119
120
-
Here the`.catch`block finishes normally. So the next successful `.then` handler is called.
120
+
Aqui el`.catch`termina de forma correcta. Entonces se ejecuta el siguiente manejador exitoso `.then`.
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
+
En el siguiente ejemplo podemos ver otra situación con `.catch`. El manejador`(*)`detecta el error y simplemente no puede manejarlo (en el ejemplo solo sabe que hacer con un `URIError`), por lo que lo lanza nuevamente:
123
123
124
124
```js run
125
-
//the execution: catch -> catch
125
+
//Ejecución: catch -> catch
126
126
newPromise((resolve, reject) => {
127
127
128
128
thrownewError("Whoops!");
129
129
130
130
}).catch(function(error) { // (*)
131
131
132
132
if (error instanceofURIError) {
133
-
//handle it
133
+
//Aqui se manejaría el error
134
134
} else {
135
-
alert("Can't handle such error");
135
+
alert("No puedo manejar este error");
136
136
137
137
*!*
138
-
throw error; //throwing this or another error jumps to the next catch
138
+
throw error; //Lanza este error u otro error que salte en el siguiente catch.
139
139
*/!*
140
140
}
141
141
142
142
}).then(function() {
143
-
/*doesn't run here*/
143
+
/*Esto no se ejecuta*/
144
144
}).catch(error=> { // (**)
145
145
146
-
alert(`The unknown error has occurred: ${error}`);
147
-
//don't return anything => execution goes the normal way
146
+
alert(`Ocurrió un error desconocido: ${error}`);
147
+
//No se devuelve nada => La ejecución continúa de forma normal
148
148
149
149
});
150
150
```
151
151
152
-
The execution jumps from the first `.catch``(*)`to the next one `(**)`down the chain.
152
+
La ejecución salta del primer `.catch``(*)`al siguiente `(**)`en la cadena.
153
153
154
-
## Unhandled rejections
154
+
## Rechazos no manejados
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 sucede cuanto un error no es manejado? Por ejemplo, si olvidamos agregar `.catch`al final de una cadena de promesas, como aquí:
157
157
158
158
```js untrusted run refresh
159
159
newPromise(function() {
160
-
noSuchFunction(); //Error here (no such function)
160
+
noSuchFunction(); //Aquí hay un error (no existe la función)
161
161
})
162
162
.then(() => {
163
-
//successful promise handlers, one or more
164
-
}); //without .catch at the end!
163
+
//manejador de una o más promesas existosas
164
+
}); //sin .catch al final!
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 caso de que se genere un error, la promesa se rechaza y la ejecución salta al manejador de rechazos más cercano. Pero aquí no hay ninguno. Entonces el error se "atasca", ya que no hay código para manejarlo.
168
168
169
-
In practice, just like with regular unhandled errors in code, it means that something has gone terribly wrong.
169
+
En la práctica, al igual que con los errores comunes no manejados en el código, esto significa que algo ha salido terriblemente mal.
170
170
171
-
What happens when a regular error occurs and is not caught by`try..catch`? The script dies with a message in the console. A similar thing happens with unhandled promise rejections.
171
+
¿Que sucede cuando ocurre un error regular y no es detectado por`try..catch`? El script muere con un mensaje en la consola. Algo similar sucede con los rechazos de promesas no manejadas.
172
172
173
-
The 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
+
En este caso, el motor de JavaScript rastrea el rechazo y lo envía al ámbito global. Puedes ver en consola el error generado si ejecutas el ejemplo anterior.
174
174
175
-
In the browser we can catch such errors using the event`unhandledrejection`:
175
+
En el navegador podemos detectar tales errores usando el evento`unhandledrejection`:
alert(event.promise); // [object Promise] - the promise that generated the error
182
-
alert(event.reason); // Error: Whoops! - the unhandled error object
180
+
//el objeto event tiene dos propiedades especiales:
181
+
alert(event.promise); // [objeto Promesa] - La promesa que fue rechazada
182
+
alert(event.reason); // Error: Whoops! - Motivo por el cual se rechaza la promesa
183
183
});
184
184
*/!*
185
185
186
186
newPromise(function() {
187
187
thrownewError("Whoops!");
188
-
}); //no catch to handle the error
188
+
}); //No hay un .catch final para manejar el 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
+
Este evento es parte del [standard HTML](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections).
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 se produce un error, y no hay un `.catch`, se dispara `unhandledrejection`, y se obtiene el objeto`event`el cual contiene información sobre el error, por lo que podemos hacer algo con el error (manejar el error).
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
+
Usualmente estos errores no son recuperables, por lo que la mejor salida es informar al usuario sobre el problema y probablemente reportar el incidente al servidor.
196
196
197
-
In non-browser environments like Node.js there are other ways to track unhandled errors.
197
+
En entornos fuera del navegador como Node.js existen otras formas de rastrear errores no manejados.
198
198
199
-
## Summary
199
+
## Resumen
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 them, so that our app never "just dies".
201
+
-`.catch`maneja errores de todo tipo: ya sea una llamada a `reject()`, o un error que arroja un manejador.
202
+
-Debemos colocar `.catch`exáctamente en los lugares donde queremos manejar los errores y saber como manejarlos. El manejador analiza los errores (los errores personalizados) y, (en caso de no conocerse la razón del error) se lanzan los errores desconocidos (tal vez sean errores de programación).
203
+
-Está bien no usar siempre`.catch`, si no hay forma de recuperarse de un error.
204
+
-En cualquier caso, deberíamos tener el evento`unhandledrejection`(para navegadores, o el equivalente en otros entornos) para rastrear errores no manejados e informar al usuario (y probablemente al servidor) para que nuestra aplicación nunca "simplemente muera".
0 commit comments