Skip to content
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

feat: Add custom exceptions #847

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
45 changes: 45 additions & 0 deletions docs_src/src/pages/documentation/api_reference/exceptions.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,48 @@
## Handling Errors

Batman learned how to handle the error for different exception in his application. He wrote the following code to handle exceptions :

<Row>
<Col>
</Col>
<Col sticky>

<CodeGroup title="Request" tag="GET" label="/hello_world/{item_id}">

```python {{ title: 'untyped' }}
from robyn import Robyn, HTTPException, status_codes

app = Robyn(__file__)

items = {"foo": "The Foo Wrestlers"}

@app.get("/hello_world/{item_id}")
async def read_item(request, item_id):
if item_id not in items:
raise HTTPException(status_code=status_codes.HTTP_404_NOT_FOUND, detail="Item not found")
return {"item": items[item_id]}
```

```python {{ title: 'typed' }}
from robyn import Robyn, HTTPException, Request, status_codes
from typing import Dict

app = Robyn(__file__)

items: Dict[str, str] = {"foo": "The Foo Wrestlers"}


@app.get("/hello_world/{item_id}")
async def read_item(request: Request, item_id: str) -> Dict[str, str]:
if item_id not in items:
raise HTTPException(status_code=status_codes.HTTP_404_NOT_FOUND, detail="Item not found")
return {"item": items[item_id]}

```
</CodeGroup>
</Col>
</Row>

## Custom Exception Handler

Batman learned how to create custom error handlers for different exception types in his application. He wrote the following code to handle exceptions and return a custom error response:
Expand Down
3 changes: 3 additions & 0 deletions robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from robyn.router import MiddlewareRouter, MiddlewareType, Router, WebSocketRouter
from robyn.types import Directory
from robyn import status_codes
from robyn.exceptions import HTTPException, WebSocketException
from robyn.ws import WebSocket
from robyn.jsonify import jsonify

Expand Down Expand Up @@ -472,6 +473,8 @@ def ALLOW_CORS(app: Robyn, origins: List[str]):
"SubRouter",
"AuthenticationHandler",
"Headers",
"HTTPException",
Mr-Sunglasses marked this conversation as resolved.
Show resolved Hide resolved
"WebSocketException",
"WebSocketConnector",
"WebSocket",
]
29 changes: 29 additions & 0 deletions robyn/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import http


class HTTPException(Exception):
def __init__(self, status_code: int, detail: str | None = None) -> None:
if detail is None:
detail = http.HTTPStatus(status_code).phrase
self.status_code = status_code
self.detail = detail

def __str__(self) -> str:
return f"{self.status_code}: {self.detail}"

def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"


class WebSocketException(Exception):
def __init__(self, code: int, reason: str | None = None) -> None:
self.code = code
self.reason = reason or ""

def __str__(self) -> str:
return f"{self.code}: {self.reason}"

def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
Loading