0
# Exception Handling
1
2
Exception and error handling classes for view lifecycle management, HTTP errors, and custom error responses with built-in error view support.
3
4
## Capabilities
5
6
### View Control Exceptions
7
8
Exceptions for controlling view execution flow and lifecycle.
9
10
```python { .api }
11
class StopReason(Exception):
12
"""Base exception for stopping view execution."""
13
14
class UserAbort(StopReason):
15
"""Raised when user aborts view execution (e.g., navigates away)."""
16
17
class ServerStop(StopReason):
18
"""Raised when server stops view execution."""
19
```
20
21
### HTTP Error Classes
22
23
Exception classes for handling HTTP error responses.
24
25
```python { .api }
26
class ForbiddenError(Exception):
27
"""Raised for 403 Forbidden errors."""
28
29
class NotFoundError(Exception):
30
"""Raised for 404 Not Found errors."""
31
32
class ClientError(Exception):
33
"""Base class for general client errors."""
34
```
35
36
### Error View Decorators
37
38
Decorators for registering custom error handling views.
39
40
```python { .api }
41
# Available on App class
42
def error_403_view(self):
43
"""Decorator for 403 error views."""
44
45
def error_404_view(self):
46
"""Decorator for 404 error views."""
47
48
def error_500_view(self):
49
"""Decorator for 500 error views."""
50
```
51
52
#### Usage Example
53
54
```python
55
from lona import App, View
56
from lona.exceptions import UserAbort, ServerStop
57
from lona.errors import NotFoundError, ForbiddenError
58
from lona.html import HTML, H1, P
59
60
app = App(__file__)
61
62
@app.route('/protected')
63
class ProtectedView(View):
64
def handle_request(self, request):
65
if not request.user:
66
raise ForbiddenError('Login required')
67
68
try:
69
# Interactive view that might be aborted
70
button = Button('Click me')
71
self.show(HTML(H1('Protected Area'), button))
72
self.await_click(button)
73
74
except UserAbort:
75
# User navigated away - cleanup if needed
76
self.cleanup_resources()
77
return
78
79
except ServerStop:
80
# Server is shutting down
81
return
82
83
# Custom error views
84
@app.error_404_view()
85
class NotFoundView(View):
86
def handle_request(self, request):
87
return HTML(
88
H1('Page Not Found'),
89
P('The requested page could not be found.')
90
)
91
92
@app.error_403_view()
93
class ForbiddenView(View):
94
def handle_request(self, request):
95
return HTML(
96
H1('Access Denied'),
97
P('You do not have permission to access this resource.')
98
)
99
```
100
101
## Types
102
103
```python { .api }
104
from typing import Optional, Union
105
106
ErrorMessage = str
107
HTTPStatus = int
108
ErrorContext = Optional[dict]
109
```