Skip to content

Commit 2dfdbb3

Browse files
authored
Merge pull request #329 from george28cs/promises-error-handling
Error handling with promises
2 parents 326527e + e51ca46 commit 2dfdbb3

File tree

4 files changed

+66
-66
lines changed

4 files changed

+66
-66
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 respuesta es: **no, no lo hará**:
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+
Como vimos en el capítulo, hay un "`try..catch` implícito" en el código de la función. Así se manejan todos los errores síncronos.
1212

13-
But here the error is generated not while the executor is running, but later. So the promise can't handle it.
13+
Pero aquí el error no se genera mientras el ejecutor está corriendo, sino más tarde. Entonces la promesa no puede manejarlo.

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+
# Error en setTimeout
22

3-
What do you think? Will the `.catch` trigger? Explain your answer.
3+
¿Qué crees que pasará? ¿Se disparará el `.catch`? Explica tu respuesta.
44

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

2-
# Error handling with promises
2+
# Manejo de errores con promesas
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+
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.
55

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:
77

88
```js run
99
*!*
10-
fetch('https://no-such-server.blabla') // rejects
10+
fetch('https://no-such-server.blabla') // Promesa rechazada
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 (El texto puede variar, dependiendo del error)
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+
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`.
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+
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:
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+
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.
4242

43-
## Implicit try..catch
43+
## try..catch implícito
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+
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.
4646

47-
For instance, this code:
47+
Por ejemplo, este código:
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+
...Hace exactamente lo mismo que este:
5858

5959
```js run
6060
new Promise((resolve, reject) => {
@@ -64,141 +64,141 @@ 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+
El "`try..catch` invisible" embebido en el ejecutor detecta automáticamente el error y lo convierte en una promesa rechazada.
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+
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.
7070

71-
Here's an example:
71+
Por ejemplo:
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!"); // rechaza la promesa
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+
Esto sucede con todos los errores, no solo los causados por la sentencia de excepción `throw`. Por ejemplo, un error de programación:
8484

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

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.
9696

97-
## Rethrowing
97+
## Rethrowing (relanzamiento de errores)
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+
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.
100100

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.
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 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.
104104

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:
106106

107107
```js run
108-
// the execution: catch -> then
108+
// Ejecución: catch -> then
109109
new Promise((resolve, reject) => {
110110

111111
throw new Error("Whoops!");
112112

113113
}).catch(function(error) {
114114

115-
alert("The error is handled, continue normally");
115+
alert("Error manejado, se continuará con la ejecución del código");
116116

117-
}).then(() => alert("Next successful handler runs"));
117+
}).then(() => alert("El siguiente manejador exitoso se ejecuta"));
118118
```
119119

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`.
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+
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:
123123

124124
```js run
125-
// the execution: catch -> catch
125+
// Ejecución: catch -> catch
126126
new Promise((resolve, reject) => {
127127

128128
throw new Error("Whoops!");
129129

130130
}).catch(function(error) { // (*)
131131

132132
if (error instanceof URIError) {
133-
// handle it
133+
// Aqui se manejaría el error
134134
} else {
135-
alert("Can't handle such error");
135+
alert("No puedo manejar este error");
136136

137137
*!*
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.
139139
*/!*
140140
}
141141

142142
}).then(function() {
143-
/* doesn't run here */
143+
/* Esto no se ejecuta */
144144
}).catch(error => { // (**)
145145

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
148148

149149
});
150150
```
151151

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.
153153

154-
## Unhandled rejections
154+
## Rechazos no manejados
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 sucede cuanto un error no es manejado? Por ejemplo, si olvidamos agregar `.catch` al final de una cadena de promesas, como aquí:
157157

158158
```js untrusted run refresh
159159
new Promise(function() {
160-
noSuchFunction(); // Error here (no such function)
160+
noSuchFunction(); // Aquí hay un error (no existe la función)
161161
})
162162
.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!
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 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.
168168

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.
170170

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.
172172

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.
174174

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`:
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+
// 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
183183
});
184184
*/!*
185185

186186
new Promise(function() {
187187
throw new Error("Whoops!");
188-
}); // no catch to handle the error
188+
}); // No hay un .catch final para manejar el 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+
Este evento es parte del [standard HTML](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections).
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 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).
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+
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.
196196

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.
198198

199-
## Summary
199+
## Resumen
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 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".
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
function getMessage() {
2-
return "Hello, world!";
2+
return "Hola, Mundo!";
33
}

0 commit comments

Comments
 (0)