Skip to content

Latest commit

 

History

History
73 lines (51 loc) · 1.87 KB

File metadata and controls

73 lines (51 loc) · 1.87 KB

Handling Errors

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

<CodeGroup title="Request" tag="GET" label="/items/:item_id">

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

app = Robyn(__file__)

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

@app.get("/items/: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("/items/: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>

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:

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

```python
@app.exception
def handle_exception(error: Exception):
    return Response(status_code=500, description=f"error msg: {error}", headers={})
```
</CodeGroup>

What's next?

Now, Batman wanted to scale his application across multiple cores. Robyn led him to Scaling.