> 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/es/api/error-handling.md).

# Gestión de errores

De forma predeterminada, los endpoints devolverán un mensaje 200 OK incluso si hay errores. Si se produce un error, obtendrá una respuesta vacía del endpoint. Este documento muestra distintas formas de gestionar los errores en las API.

## Devolver errores automáticamente

Para devolver errores automáticamente desde las API, puede cambiar el comportamiento predeterminado estableciendo el parámetro `-ErrorAction` de `New-PSUEndpoint` en `Stop`. Cualquier error provocará que se devuelva un error 500 Internal Server Error con una lista de los errores y el seguimiento de la pila.

Los errores de terminación siempre devolverán un error 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
```

Observará un comportamiento diferente en Windows PowerShell y PowerShell 7 al llamar a API REST que devuelven errores. En Windows PowerShell, recibirá un error genérico que no devuelve el mensaje de error.

```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
```

En PowerShell 7, cuando se devuelve un error, verá el mensaje de error devuelto.

```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
```

Puede recuperar el mensaje de error en Windows PowerShell utilizando la siguiente sintaxis.

```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
```

## Devolver errores manualmente

Para devolver errores manualmente, debe utilizar el cmdlet `New-PSUApiResponse`. Este cmdlet le permite definir el código de estado y el cuerpo de la respuesta.

En este ejemplo, devolvemos un código de error 404 desde el endpoint.

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

De forma similar a los códigos de error automáticos, los códigos de error devueltos manualmente se mostrarán mejor en PowerShell 7. Aquí tiene un ejemplo de llamada al endpoint.

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

Invoke-RestMethod: Failed!
```

Si se llama desde Windows PowerShell, recibirá un error similar al que se devuelve automáticamente.

```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
```

Puede elegir devolver códigos de error si se cumplen determinadas condiciones utilizando su script de PowerShell dentro del 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/es/comandos-de-powershell/new-psuendpoint.md)
* [Get-PSUEndpoint](/powershell-universal/es/comandos-de-powershell/get-psuendpoint.md)
* [Remove-PSUEndpoint](/powershell-universal/es/comandos-de-powershell/remove-psuendpoint.md)
* [New-PSUApiResponse](/powershell-universal/es/comandos-de-powershell/new-psuapiresponse.md)
* [Set-PSUSetting](/powershell-universal/es/comandos-de-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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
