diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md index 31bc6d328..2802653d2 100644 --- a/docs/de/docs/tutorial/handling-errors.md +++ b/docs/de/docs/tutorial/handling-errors.md @@ -19,6 +19,58 @@ Die Statuscodes im 400er-Bereich bedeuten hingegen, dass es einen Fehler gab. Erinnern Sie sich an all diese **404 Not Found** Fehler (und Witze)? +## Fehlerüberwachungstools + +Sentry ist ein Anwendungsüberwachungsdienst, der Entwicklern hilft, Probleme in Echtzeit zu identifizieren und zu beheben. Sentry bietet: + +* Fehlergruppierung zur Aggregation ähnlicher Fehler +* Quellcode-Kontext aus Stack-Traces +* Detaillierte Anfrageinformationen +* Leistungsüberwachung für Webanfragen, Datenbankabfragen und mehr +* Verteiltes Tracing, um zu verstehen, wie sich Fehler über den Stack ausbreiten + +Um Sentry mit FastAPI zu verwenden, installieren Sie zuerst das SDK: + +```bash +pip install --upgrade 'sentry-sdk[fastapi]' +``` + +Initialisieren Sie dann Sentry in Ihrer Anwendung: + +```python +import sentry_sdk +from fastapi import FastAPI + +sentry_sdk.init( + dsn="your-dsn-here", + # Setzen Sie traces_sample_rate, um den Prozentsatz der an Sentry zu sendenden Traces zu konfigurieren, wobei 1.0 100% entspricht + traces_sample_rate=1.0, +) + +app = FastAPI() + +# Ihr FastAPI-Code hier +``` + +Sentry erfasst automatisch unbehandelte Ausnahmen, aber Sie können auch explizit Ausnahmen erfassen und benutzerdefinierte Events senden: + +```python +@app.get("/items/{item_id}") +async def read_item(item_id: int): + try: + # Ihr Code, der fehlschlagen könnte + if item_id == 0: + raise ValueError("Item ID kann nicht Null sein") + # ... + except Exception as e: + # Erfassen Sie die Ausnahme + sentry_sdk.capture_exception(e) + # Sie können die Ausnahme weiterhin normal behandeln + raise HTTPException(status_code=500, detail="Interner Serverfehler") +``` + +Weitere Informationen finden Sie in der Sentry FastAPI-Integrationsdokumentation. + ## `HTTPException` verwenden Um HTTP-Responses mit Fehlern zum Client zurückzugeben, verwenden Sie `HTTPException`. @@ -51,7 +103,7 @@ Wenn der Client `http://example.com/items/foo` anfragt (ein `item_id` `"foo"`), } ``` -Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der „Not Found“-Fehler), und eine JSON-Response wie folgt: +Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der "Not Found"-Fehler), und eine JSON-Response wie folgt: ```JSON { @@ -166,7 +218,7 @@ Das folgende sind technische Details, die Sie überspringen können, wenn sie f **FastAPI** verwendet diesen, sodass Sie, wenn Sie ein Pydantic-Modell für `response_model` verwenden, und ihre Daten fehlerhaft sind, einen Fehler in ihrem Log sehen. -Aber der Client/Benutzer sieht ihn nicht. Stattdessen erhält der Client einen „Internal Server Error“ mit einem HTTP-Statuscode `500`. +Aber der Client/Benutzer sieht ihn nicht. Stattdessen erhält der Client einen ""Internal Server Error"" mit einem HTTP-Statuscode `500`. Das ist, wie es sein sollte, denn wenn Sie einen Pydantic-`ValidationError` in Ihrer *Response* oder irgendwo sonst in ihrem Code haben (es sei denn, im *Request* des Clients), ist das tatsächlich ein Bug in ihrem Code. @@ -230,7 +282,7 @@ Sie erhalten eine Response, die Ihnen sagt, dass die Daten ungültig sind, und w **FastAPI** hat seine eigene `HTTPException`. -Und **FastAPI**s `HTTPException`-Fehlerklasse erbt von Starlettes `HTTPException`-Fehlerklasse. +Und **FastAPIs** `HTTPException`-Fehlerklasse erbt von Starlettes `HTTPException`-Fehlerklasse. Der einzige Unterschied besteht darin, dass **FastAPIs** `HTTPException` alles für das Feld `detail` akzeptiert, was nach JSON konvertiert werden kann, während Starlettes `HTTPException` nur Strings zulässt. diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 4d969747f..170908a63 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -19,6 +19,58 @@ The status codes in the 400 range mean that there was an error from the client. Remember all those **"404 Not Found"** errors (and jokes)? +## Error Monitoring Tools + +Sentry is an application monitoring service that helps developers identify and fix issues in real-time. Sentry provides: + +* Error grouping to aggregate similar errors +* Source code context from stack traces +* Detailed request information +* Performance monitoring for web requests, database queries, and more +* Distributed tracing to understand how errors propagate across your stack + +To use Sentry with FastAPI, first install the SDK: + +```bash +pip install --upgrade 'sentry-sdk[fastapi]' +``` + +Then initialize Sentry in your application: + +```python +import sentry_sdk +from fastapi import FastAPI + +sentry_sdk.init( + dsn="your-dsn-here", + # Set traces_sample_rate to configure the percent of traces to send to Sentry, where 1.0 is 100% + traces_sample_rate=1.0, +) + +app = FastAPI() + +# Your FastAPI code here +``` + +Sentry will automatically capture unhandled exceptions, but you can also explicitly capture exceptions and send custom events: + +```python +@app.get("/items/{item_id}") +async def read_item(item_id: int): + try: + # Your code that might fail + if item_id == 0: + raise ValueError("Item ID cannot be zero") + # ... + except Exception as e: + # Capture the exception + sentry_sdk.capture_exception(e) + # You can still handle the exception normally + raise HTTPException(status_code=500, detail="Internal server error") +``` + +For more information, see the Sentry FastAPI integration documentation. + ## Use `HTTPException` To return HTTP responses with errors to the client you use `HTTPException`. diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md index 2e4464989..cba67f93f 100644 --- a/docs/es/docs/tutorial/handling-errors.md +++ b/docs/es/docs/tutorial/handling-errors.md @@ -19,6 +19,58 @@ Los códigos de estado en el rango de 400 significan que hubo un error por parte ¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)? +## Herramientas de Monitoreo de Errores + +Sentry es un servicio de monitoreo de aplicaciones que ayuda a los desarrolladores a identificar y solucionar problemas en tiempo real. Sentry proporciona: + +* Agrupación de errores para agregar errores similares +* Contexto del código fuente de los rastros de pila +* Información detallada de las solicitudes +* Monitoreo de rendimiento para solicitudes web, consultas de bases de datos y más +* Rastreo distribuido para entender cómo se propagan los errores a través de su stack + +Para usar Sentry con FastAPI, primero instale el SDK: + +```bash +pip install --upgrade 'sentry-sdk[fastapi]' +``` + +Luego inicialice Sentry en su aplicación: + +```python +import sentry_sdk +from fastapi import FastAPI + +sentry_sdk.init( + dsn="your-dsn-here", + # Configure traces_sample_rate para establecer el porcentaje de trazas a enviar a Sentry, donde 1.0 es 100% + traces_sample_rate=1.0, +) + +app = FastAPI() + +# Su código FastAPI aquí +``` + +Sentry capturará automáticamente las excepciones no manejadas, pero también puede capturar excepciones explícitamente y enviar eventos personalizados: + +```python +@app.get("/items/{item_id}") +async def read_item(item_id: int): + try: + # Su código que podría fallar + if item_id == 0: + raise ValueError("El ID del ítem no puede ser cero") + # ... + except Exception as e: + # Capture la excepción + sentry_sdk.capture_exception(e) + # Aún puede manejar la excepción normalmente + raise HTTPException(status_code=500, detail="Error interno del servidor") +``` + +Para más información, consulte la documentación de integración de Sentry para FastAPI. + ## Usa `HTTPException` Para devolver responses HTTP con errores al cliente, usa `HTTPException`.