> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/powershell-universal/it/api/error-handling.md).

# Gestione degli errori

Gestisca gli errori nelle API REST di PowerShell Universal configurando ErrorAction, restituendo codici di stato personalizzati e leggendo gli errori in Windows PowerShell.

Per impostazione predefinita, gli endpoint restituiscono un messaggio 200 OK anche in presenza di errori. Se si verifica un errore, riceverà una risposta vuota dall'endpoint. Questo documento illustra diversi modi per gestire gli errori all'interno delle API.

## Restituzione automatica degli errori

Per restituire automaticamente gli errori dalle API, può modificare il comportamento predefinito impostando il parametro `-ErrorAction` di `New-PSUEndpoint` su `Stop`. Qualsiasi errore comporterà la restituzione di un 500 Internal Server Error con un elenco degli errori e lo stack trace.

Gli errori di tipo terminating restituiranno sempre un 500 Internal Server Error.

```powershell
New-PSUEndpoint -Url "/error" -Endpoint { 
   throw "Uh oh!"
} -ErrorAction stop

New-PSUEndpoint -Url /error2 -Endpoint {
    Write-Error "Whoa!"
} -ErrorAction Stop
```

Noterà un comportamento diverso in Windows PowerShell e in PowerShell 7 quando chiama API REST che restituiscono errori. In Windows PowerShell riceverà un errore generico che non restituisce il messaggio di errore.

```powershell
PS C:\Users\adamr> invoke-restmethod http://localhost:5000/error2
invoke-restmethod : The remote server returned an error: (500) Internal Server Error.
At line:1 char:1
+ invoke-restmethod http://localhost:5000/error2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], Web
   Exception
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
```

In PowerShell 7, quando viene restituito un errore, vedrà il messaggio di errore restituito.

```powershell
PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/error 

Invoke-RestMethod: Uh oh!
at , : line 2
at , : line 1

PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/error2

Invoke-RestMethod: Whoa
at , : line 2
at , : line 1
```

Può recuperare il messaggio di errore in Windows PowerShell utilizzando la sintassi seguente.

```powershell
PS C:\Users\adamr> try { invoke-restmethod http://localhost:5000/error2 } catch { [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream()).ReadToEnd()}
Whoa!
at <ScriptBlock>, <No file>: line 2
at <ScriptBlock>, <No file>: line 1
```

## Restituzione manuale degli errori

Per restituire manualmente gli errori, deve utilizzare il cmdlet `New-PSUApiResponse`. Questo cmdlet consente di definire il codice di stato e il corpo della risposta.

In questo esempio restituiamo un codice di errore 404 dall'endpoint.

```powershell
New-PSUEndpoint -Url /broken -Endpoint {
    New-PSUApiResponse -StatusCode 404 -Body 'Failed!'
}
```

Analogamente ai codici di errore automatici, i codici di errore restituiti manualmente vengono visualizzati meglio in PowerShell 7. Ecco un esempio di chiamata all'endpoint.

```powershell
PS C:\Users\adamr\Desktop> invoke-restmethod http://localhost:5000/broken

Invoke-RestMethod: Failed!
```

Se chiamato da Windows PowerShell, riceverà un errore simile a quello restituito automaticamente.

```powershell
PS C:\Users\adamr> invoke-restmethod http://localhost:5000/broken
invoke-restmethod : The remote server returned an error: (404) Not Found.
At line:1 char:1
+ invoke-restmethod http://localhost:5000/broken
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], Web
   Exception
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
```

Può scegliere di restituire codici di errore se sono soddisfatte determinate condizioni, utilizzando il suo script PowerShell all'interno dell'endpoint.

```powershell
New-PSUEndpoint -Url /user/:name -Endpoint {
    if ($Name -eq 'User')
    {
        @{ UserName = "Adam" }
    }
    else
    {
        New-PSUApiResponse -StatusCode 404 -Body 'Unknown user!'    
    }

}
```

## API

* [New-PSUEndpoint](/powershell-universal/it/comandi-powershell/new-psuendpoint.md)
* [Get-PSUEndpoint](/powershell-universal/it/comandi-powershell/get-psuendpoint.md)
* [Remove-PSUEndpoint](/powershell-universal/it/comandi-powershell/remove-psuendpoint.md)
* [New-PSUApiResponse](/powershell-universal/it/comandi-powershell/new-psuapiresponse.md)
* [Set-PSUSetting](/powershell-universal/it/comandi-powershell/set-psusetting.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.devolutions.net/powershell-universal/it/api/error-handling.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
