Skip to content

Error boundaries translation #279

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 15 commits into from
Apr 26, 2021
Merged
Changes from 1 commit
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
83 changes: 42 additions & 41 deletions content/docs/error-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,26 @@ title: Contenitori di Errori
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.
In passato gli errori JavaScript all'interno dei componenti erano usati per corrompere lo stato interno di React e causavano l'[emissione](https://github.com/facebook/react/issues/4026) di [errori](https://github.com/facebook/react/issues/8579) [criptici](https://github.com/facebook/react/issues/6895) nei rendering successivi. Questi errori erano sempre causati da un errore precedente nel codice dell'applicazione, ma React non forniva nessun modo per poterli gestire correttamente nei componenti e non poteva ripristinarli.


## Introducing Error Boundaries {#introducing-error-boundaries}
## Introduzione ai contenitori di errori {#introducing-error-boundaries}

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.
Un errore JavaScript in una qualche parte della UI non dovrebbe rompere l'intera applicazione. Per risolvere questo problema, a partire dalla versione 16 di React, viene introdotto il concetto di "contenitore di errori (error boundary)".

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.
I contenitori di errori sono componenti React che **catturano gli errori JavaScript in uno qualsiasi dei componenti figli nell'albero dei componenti, loggano gli errori e mostrano, all'utente, una UI di fallback** anziché mostrare il componente che ha causato l'errore. I contenitori di errore catturano gli errori durante il rendering, nei metodi del ciclo di vita di un componente e nei costruttori dell'intero albero di componenti sottostante.

> Note
> Nota
>
> Error boundaries do **not** catch errors for:
> I contenitori di errore non catturano gli errori di:
>
> * 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)
> * Gestore di eventi ([approfondisci](#how-about-event-handlers))
> * Codice asincrono (come ad esempio le callback `setTimeout` o `requestAnimationFrame`)
> * Rendering lato server
> * Errori sollevati all'interno del contenitore stesso (piuttosto che nei suoi figli)

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 basato su classe diventa un contenitore di errori se definisce uno, o entrambi, i metodi del ciclo di vita [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) e [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Utilizza `static getDerivedStateFromError()` per renderizzare una UI di fallback dopo che l'errore è stato sollevato. Utilizzate `componentDidCatch()` per loggare informazioni sull'errore.

```js{7-10,12-15,18-21}
class ErrorBoundary extends React.Component {
Expand Down Expand Up @@ -52,61 +53,61 @@ class ErrorBoundary extends React.Component {
}
```

Then you can use it as a regular component:
Dopodiché lo si può utilizzare come un normalissimo componente:

```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.
I contenitori di errore lavorano all'incirca come il `catch {}` di JavaScript, ma sottoforma di componente. Solamente i componenti di tipo classe possono essere contenitori di errori. In pratica, nella maggioranza dei casi, si vuole scrivere un contenitore di errori una sola volta, per poi riutilizzarlo ovunque nell'applicazione.

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.
Da notare che **i contenitori di errori catturano gli errori solo nei componenti sottostanti nell'albero dei componenti** Un contenitore di errori non può catturare errori all'interno di se stesso. Se un contenitore di errore fallisce mentre prova a renderizzare il messaggio di errore, l'errore viene propagato sopra di lui al più vicino contenitore di errori sopra di lui. Anche questo aspetto è molto simile a come funzione il blocco `catch {}` di JavaScript.

## Live Demo {#live-demo}
## 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).
Guarda [questo esempio di dichiarazione e utilizzo di un contenitore di errori](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) fatto con [React 16](/blog/2017/09/26/react-v16.0.html).


## Where to Place Error Boundaries {#where-to-place-error-boundaries}
## Dove si dichiarano i contenitori di errori? {#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 how 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.
La granularità dei contenitori di errori dipende interamente da te sviluppatore. Potresti voler wrappare i componenti di rotte di primo livello facendo vedere un messaggio, all'utente, tipo "Qualcosa è andato storto" proprio come i framework lato server, spesso, gestiscono i crash. Potresti anche voler wrappare singoli widget all'interno di un contenitore di errori per proteggerli dai crash che possono succedere all'interno dell'applicazione.


## New Behavior for Uncaught Errors {#new-behavior-for-uncaught-errors}
## Nuovi comportamenti per errori non rilevati {#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.**
Questi cambiamenti hanno un'importante implicazione. **A partire dalla versione 16 di React, gli errori che non vengono catturati da nessun contenitore di errori, porteranno allo smontaggio dell'intero albero dei componenti di 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.
Abbiamo discusso molto prima di prendere questa decisione ma, secondo la nostra esperienza è peggio lasciare una UI rotta piuttosto che rimuoverla completamente. Ad esempio, in prodotti come Messenger, lasciare visibile una UI rotta può portare qualcuno a mandare un messaggio alla persona sbagliata. In modo simile, in un'applicazione di pagamenti è peggiore mostrare un importo sbagliato piuttosto che non far vedere nulla.

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.
Questi cambiamenti significano che se migrate verso React 16 probabilmente scoprirete, all'interno della vostra applicazione, dei crash che prima venivano ignorati. Aggiungere contenitori di errori vi aiuta a fornire una migliore user experience quando qualcosa va storto.

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.
Ad esempio Facebook Messenger wrappa il contenuto della barra laterale, del pannello informativo, delle conversazioni e dei messaggi di input in contenitori di errori separati. Se qualche componente in una delle precedenti aree si rompo, il resto dell'applicazione rimane comunque interattiva.

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.
Vi incoraggiamo inoltre ad utilizzare dei servizi JavaScript di reportistica (o costruitene una personalizzato) cosicché da capire che tipo di eccezioni vengono sollevate in produzione, e che non vengono catturate, e fixarle.


## Component Stack Traces {#component-stack-traces}
## Stack trace dei componenti {#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:
La versione 16 di React stampa tutti gli errori, che vengono sollevati durante il rendering, nella console degli sviluppatori, anche se l'applicazione accidentamente li nasconde. Oltre al messaggio di errore, e allo stack JavaScript, React 16 fornisce anche lo stack trace dei componenti. Si può vedere esattamente dove, nell'albero dei componenti, sta l'errore:

<img src="../images/docs/error-boundaries-stack-trace.png" style="max-width:100%" alt="Error caught by Error Boundary component">

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:
E' anche possibile vedere i nomi dei fili e i numeri di linea nello stack trace del componente. Questo è il comportamento di default nei progetti creati con [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">

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**.
Se avete creato l'applicazione senza usare Create React App, potete usare [questo plugin] da aggiungere, manualmente, alla configurazione Babel. Tieni presente che tutto ciò vale solo per l'ambiente di sviluppo e **deve essere disabilitato in produzione**.

> 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.
> I nomi dei componenti visualizzati nello stack trace dipendono dalla proprietà [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name). Se fornite supporto a browser vecchi che non forniscono questa cosa nativamente (come ad esempio IE 11), potete prendere in considerazione di includere il polyfill `Function.name` all'interno del bundle dell'applicazione, come ad esempio [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternativamente possiamo, esplicitamente, settare la proprietà [`displayName`](/docs/react-component.html#displayname) su tutti i componenti.


## How About try/catch? {#how-about-trycatch}
## Che dire di try/catch? {#how-about-trycatch}

`try` / `catch` is great but it only works for imperative code:
`try` / `catch` è ottimo ma funziona solo per codice imperativo:

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

However, React components are declarative and specify *what* should be rendered:
Tuttavia i compoenti di React sono molto dichiarativi e specificano cosa deve essere renderizzato:

```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.
I contenitori di errore preservano la natura dichiarativa di React e si comporta esattamente come ci si aspetta. Ad esempio, anche se l'errore capita nel metodo `componentDidUpdate`, causato da `setState` sollevato da qualche parte in profondità nell'albero, continuerà a propagare correttamente l'errore al più vicino contenitore di errori.

## How About Event Handlers? {#how-about-event-handlers}
## Che dire del gestore degli eventi? {#how-about-event-handlers}

Error boundaries **do not** catch errors inside event handlers.
I contenitori di errori **non catturano** gli errori all'interno dei gestori degli eventi.

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 non ha necessità di contenutori di errori per il gestore degli eventi. A differenza dei metodi di render e dei metodi del ciclo di vita, i gestori degli eventi non si hanno durante il rendering. Quindi se questi lanciano un errore, React continua comunque a sapere cosa visualizzare sullo schermo.

If you need to catch an error inside an event handler, use the regular JavaScript `try` / `catch` statement:
Se hai bisogno di catturare un errore all'interno di un gestore degli eventi, utilizza il `try` / `catch` di JavaScript:

```js{9-13,17-20}
class MyComponent extends React.Component {
Expand All @@ -157,10 +158,10 @@ class MyComponent extends React.Component {
}
```

Note that the above example is demonstrating regular JavaScript behavior and doesn't use error boundaries.
Notate che l'esempio di codice precedente mostra il regolare comportamento di JavaScript e non usa contenitori di errori.

## Naming Changes from React 15 {#naming-changes-from-react-15}
## Cambiamenti di nome a partire da 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.
La versione 15 di React include un limitato supporto per i contenitori di errori sotto diversi nomi: `unstable_handleError`. Questo metodo non funziona più e dovresti sostituirlo con `componentDidCatch` a partire dalla versione 16 beta.

For this change, we’ve provided a [codemod](https://github.com/reactjs/react-codemod#error-boundaries) to automatically migrate your code.
Per questi cambiamenti, viene fornito [codemod](https://github.com/reactjs/react-codemod#error-boundaries) che automaticamente migra il tuo codice.