Skip to content

translate error boundaries documentation to spanish #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 22, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 48 additions & 50 deletions content/docs/error-boundaries.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
---
id: error-boundaries
title: Error Boundaries
title: Límites de errores
permalink: docs/error-boundaries.html
---

In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to [emit](https://github.com/facebook/react/issues/4026) [cryptic](https://github.com/facebook/react/issues/6895) [errors](https://github.com/facebook/react/issues/8579) on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them.
En el pasado, los errores de JavaScript dentro de los componentes solían corromper el estado interno de React y hacían que [emitiera](https://github.com/facebook/react/issues/4026) [errores](https://github.com/facebook/react/issues/6895) [crípticos](https://github.com/facebook/react/issues/8579) en siguientes renderizados. Estos errores siempre eran causados por un error previo en el código de aplicación, pero React no proveía una manera de gestionarlos elegantemente en componentes, y no podía recuperarse de ellos.

## Introduciendo Límites de Errores {#introducing-error-boundaries}

## Introducing Error Boundaries {#introducing-error-boundaries}
Un error de JavaScript en una parte de la interfaz no debería romper toda la aplicación. Para resolver este problema, React 16 introduce el nuevo concepto de “límite de errores”.

A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”.
Los límites de errores son componentes de React que **capturan errores de JavaScript en cualquier parte de su árbol de componentes hijo, registran esos errores, y muestran una interfaz de repuesto** en lugar del árbol de componentes que ha fallado. Los límites de errores capturan errores durante el renderizado, en métodos del ciclo de vida, y en constructores de todo el árbol bajo ellos.

Error boundaries are React components that **catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI** instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

> Note
> Nota
>
> Error boundaries do **not** catch errors for:
> Los límites de errores **no** capturan errores de:
>
> * Event handlers ([learn more](#how-about-event-handlers))
> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks)
> * Server side rendering
> * Errors thrown in the error boundary itself (rather than its children)
> * Manejadores de eventos ([aprende más](#how-about-event-handlers))
> * Código asíncrono (p.ej. callbacks de `setTimeout` o `requestAnimationFrame`)
> * Renderizado en el servidor
> * Errores lanzados en el propio límite de errores (en lugar de en sus hijos)

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) or [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Use `static getDerivedStateFromError()` to render a fallback UI after an error has been thrown. Use `componentDidCatch()` to log error information.
Un componente de clase (class component) se convierte en límite de errores si define uno (o ambos) de los métodos del ciclo de vida [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) o [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Usa `static getDerivedStateFromError()` para renderizar una interfaz de repuesto cuando se lance un error. Usa `componentDidCatch()` para registrar información de los errores.

```js{7-10,12-15,18-21}
class ErrorBoundary extends React.Component {
Expand All @@ -32,18 +31,18 @@ class ErrorBoundary extends React.Component {
}

static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
// Actualiza el estado para que el siguiente renderizado muestre la interfaz de repuesto
return { hasError: true };
}

componentDidCatch(error, info) {
// You can also log the error to an error reporting service
// También puedes registrar el error en un servicio de reporte de errores
logErrorToMyService(error, info);
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI
// Puedes renderizar cualquier interfaz de repuesto
return <h1>Something went wrong.</h1>;
}

Expand All @@ -52,61 +51,60 @@ class ErrorBoundary extends React.Component {
}
```

Then you can use it as a regular component:
Luego puedes usarlo como un componente normal:

```js
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
```

Error boundaries work like a JavaScript `catch {}` block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application.
Los límites de errores funcionan como un bloque catch{} de JavaScript, pero para componentes. Sólo los componentes de clase (class components) pueden ser límites de errores. En la práctica, la mayor parte del tiempo declararás un límite de errores una vez y lo usarás a lo largo de tu aplicación.

Note that **error boundaries only catch errors in the components below them in the tree**. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how catch {} block works in JavaScript.
Ten en cuenta que **los límites de errores sólo capturan errores en los componentes bajo ellos en el árbol**. Un límite de errores no puede capturar un error dentro de sí mismo. Si un límite de errores falla tratando de renderizar el mensaje de error, el error se propagará al límite de errores más cercano por encima de él. Esto también es similar al funcionamiento de los bloques catch{} en JavaScript.

## Live Demo {#live-demo}

Check out [this example of declaring and using an error boundary](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) with [React 16](/blog/2017/09/26/react-v16.0.html).

Mira [este ejemplo de declaración y uso de un límite de errores](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) con [React 16](/blog/2017/09/26/react-v16.0.html).

## Where to Place Error Boundaries {#where-to-place-error-boundaries}

The granularity of error boundaries is up to you. You may wrap top-level route components to display a “Something went wrong” message to the user, just like server-side frameworks often handle crashes. You may also wrap individual widgets in an error boundary to protect them from crashing the rest of the application.
## Dónde poner Límites de Errores {#where-to-place-error-boundaries}

La granularidad de los límites de errores depende de tí. Puedes envolver los componentes de enrutado de alto nivel para mostrar un mensaje de "Algo ha ido mal" al usuario, tal como a menudo gestionan los errores los frameworks del lado del servidor. También puedes envolver widgets aisladas en un límite de error para evitar que hagan fallar el resto de la aplicación.

## New Behavior for Uncaught Errors {#new-behavior-for-uncaught-errors}
## Nuevo comportamiento para los errores no capturados {#new-behavior-for-uncaught-errors}

This change has an important implication. **As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.**
Este cambio tiene una implicación importante. **A partir de React 16, los errores que no sean capturados por ningún límite de error resultarán en el desmontado de todo el árbol de componentes de React.**

We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing.
Debatimos esta decisión, pero en nuestra experiencia es peor dejar una interfaz corrompida que eliminarla completamente. Por ejemplo, en un producto como Messenger dejar la interfaz rota visible puede llevar a que alguien mande un mensaje a la persona equivocada. De manera similar, es peor que una aplicacion de pagos muestre un total erróneo a no renderizar nada.

This change means that as you migrate to React 16, you will likely uncover existing crashes in your application that have been unnoticed before. Adding error boundaries lets you provide better user experience when something goes wrong.
Este cambio significa que cuando migres a React 16, probablemente descubras fallos existentes en tu aplicación que antes habían pasado desapercibidos. Añadir límites de errores te permite dar una mejor experiencia de usuario cuando algo va mal.

For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive.
Por ejemplo, en Facebook Messenger se envuelven los contenidos de la barra lateral, el panel de información, el registro de conversaciones, y el input de mensajes en límites de errores separados. Si falla un componente en una de esas áreas de la interfaz, el resto continúan estando interactivos.

We also encourage you to use JS error reporting services (or build your own) so that you can learn about unhandled exceptions as they happen in production, and fix them.
También te animamos a que uses servicios de reporte de errores de JS (o crees el tuyo), para que puedas descubrir excepciones no controladas cuando occuren en producción y arreglarlas.


## Component Stack Traces {#component-stack-traces}
## Trazas de la pila de componentes {#component-stack-traces}

React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened:
React 16 muestra todos los errores que ocurrieron durante el rendering por consola en desarrollo, incluso si la aplicación se los traga accidentalmente. Además de las pilas de mensajes de error y de JavaScript, tambieén provee trazas de la pila de componentes. Ahora puedes ver en qué parte exactamente del árbol de componentes ha ocurrido el fallo:

<img src="../images/docs/error-boundaries-stack-trace.png" style="max-width:100%" alt="Error caught by Error Boundary component">
<img src="../images/docs/error-boundaries-stack-trace.png" style="max-width:100%" alt="Error capturado por componente Límite de Errores">

You can also see the filenames and line numbers in the component stack trace. This works by default in [Create React App](https://github.com/facebookincubator/create-react-app) projects:
También puedes ver los nombres de los ficheros y los números de línea en la traza de la pila de componentes. Esto funciona por defecto en proyectos de [Create React App](https://github.com/facebookincubator/create-react-app):

<img src="../images/docs/error-boundaries-stack-trace-line-numbers.png" style="max-width:100%" alt="Error caught by Error Boundary component with line numbers">
<img src="../images/docs/error-boundaries-stack-trace-line-numbers.png" style="max-width:100%" alt="Error capturado por componente Límite de Errores con números de línea">

If you don’t use Create React App, you can add [this plugin](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source) manually to your Babel configuration. Note that it’s intended only for development and **must be disabled in production**.
Si no usas Create React App, puedes añadir manualmente [este plugin](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source) a tu configuración de Babel. Ten en cuenta que está pensado sólo para desarrollo y **debe ser desabilitado en producción**.

> Note
> Nota
>
> Component names displayed in the stack traces depend on the [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property. If you support older browsers and devices which may not yet provide this natively (e.g. IE 11), consider including a `Function.name` polyfill in your bundled application, such as [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternatively, you may explicitly set the [`displayName`](/docs/react-component.html#displayname) property on all your components.
> Los nombres de componentes que se muestran en las trazas de pila dependen de la propiedad [`Function.name`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Function/name). Si das soporte a navegadores antiguos y dispositivos que puede que no provean esto nativamente (p.ej. IE 11), considera incluir un polyfill de `Function.name` en tu aplicación empaquetada, como [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternativamente, puedes poner la propiedad [`displayName`](/docs/react-component.html#displayname) en todos tus componentes.


## How About try/catch? {#how-about-trycatch}
## ¿Qué pasa con try/catch? {#how-about-trycatch}

`try` / `catch` is great but it only works for imperative code:
`try` / `catch` está muy bien, pero sólo funciona para código imperativo:

```js
try {
Expand All @@ -116,21 +114,21 @@ try {
}
```

However, React components are declarative and specify *what* should be rendered:
No obstante, los componentes de React son declarativos y especifican *qué* se debe renderizar:

```js
<Button />
```

Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` method caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
Los límites de errores preservan la naturaleza declarativa de React, y se comportan como esperarías. Por ejemplo, incluso si un error ocurre en un método `componentDidUpdate` causado por un `setState` en algún sitio profundo dentro del árbol, se propagará de todas formas correctamente al límite de errores más cercano.

## How About Event Handlers? {#how-about-event-handlers}
## ¿Qué pasa con los manejadores de eventos? {#how-about-event-handlers}

Error boundaries **do not** catch errors inside event handlers.
Los límites de errores **no** capturan errores en los manejadores de eventos.

React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
React no necesita límites de errores para recuperarse de errores en los manejadores de eventos. Al diferencia del método render y de los métodos del ciclo de vida, los manejadores de eventos no ocurren durante el renderizado, por lo que, si lanzan una excepción, React sigue sabiendo qué mostrar en la pantalla.

If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:
Si necesitas capturar un error dentro de un manejador de eventos, usa la sentencia de `try` / `catch` normal de JavaScript.

```js{9-13,17-20}
class MyComponent extends React.Component {
Expand All @@ -142,7 +140,7 @@ class MyComponent extends React.Component {

handleClick() {
try {
// Do something that could throw
// Hacer algo que puede lanzar una excepción
} catch (error) {
this.setState({ error });
}
Expand All @@ -157,10 +155,10 @@ class MyComponent extends React.Component {
}
```

Note that the above example is demonstrating regular JavaScript behavior and doesn't use error boundaries.
Fíjate en que el ejemplo de arriba muestra el comportamiento normal de JavaScript y no usa límites de errores.

## Naming Changes from React 15 {#naming-changes-from-react-15}
## Cambios de nomenclatura desde React 15 {#naming-changes-from-react-15}

React 15 included a very limited support for error boundaries under a different method name: `unstable_handleError`. This method no longer works, and you will need to change it to `componentDidCatch` in your code starting from the first 16 beta release.
React 15 incluía un soporte muy limitado para límites de errores con un nombre de método diferente: `unstable_handleError`. Este método ya no funciona, y necesitarás cambiarlo a `componentDidCatch` en tu código a partir del primer lanzamiento beta de la versión 16.

For this change, we’ve provided a [codemod](https://github.com/reactjs/react-codemod#error-boundaries) to automatically migrate your code.
Para este cambio, hemos provisto un [codemod](https://github.com/reactjs/react-codemod#error-boundaries) para migrar automáticamente tu código.