6176964bdf
* Reorder and clarify the 'Request Data' guide, adding a section on RequestParameters * Clarify routing guide, adding introduction and HTTP types sections * Clarify the use-cases of middleware * Clean up formatting in the exceptions guide and add some common exceptions. * Fix formatting of blueprints and add use-case example. * Clarify the class-based views guide * Clarify and fix formatting of cookies guide * Clarify static files guide * Clarify the custom protocols guide. * Add more information to the deploying guide * Fix broken list in the community extensions list. * Add introduction and improve warning to contributing guide * Expand getting started guide * Reorder guides and add links between them * Standardise heading capitalisation
50 lines
1.5 KiB
Markdown
50 lines
1.5 KiB
Markdown
# Exceptions
|
|
|
|
Exceptions can be thrown from within request handlers and will automatically be
|
|
handled by Sanic. Exceptions take a message as their first argument, and can
|
|
also take a status code to be passed back in the HTTP response.
|
|
|
|
## Throwing an exception
|
|
|
|
To throw an exception, simply `raise` the relevant exception from the
|
|
`sanic.exceptions` module.
|
|
|
|
```python
|
|
from sanic.exceptions import ServerError
|
|
|
|
@app.route('/killme')
|
|
def i_am_ready_to_die(request):
|
|
raise ServerError("Something bad happened", status_code=500)
|
|
```
|
|
|
|
## Handling exceptions
|
|
|
|
To override Sanic's default handling of an exception, the `@app.exception`
|
|
decorator is used. The decorator expects a list of exceptions to handle as
|
|
arguments. You can pass `SanicException` to catch them all! The decorated
|
|
exception handler function must take a `Request` and `Exception` object as
|
|
arguments.
|
|
|
|
```python
|
|
from sanic.response import text
|
|
from sanic.exceptions import NotFound
|
|
|
|
@app.exception(NotFound)
|
|
def ignore_404s(request, exception):
|
|
return text("Yep, I totally found the page: {}".format(request.url))
|
|
```
|
|
|
|
## Useful exceptions
|
|
|
|
Some of the most useful exceptions are presented below:
|
|
|
|
- `NotFound`: called when a suitable route for the request isn't found.
|
|
- `ServerError`: called when something goes wrong inside the server. This
|
|
usually occurs if there is an exception raised in user code.
|
|
|
|
See the `sanic.exceptions` module for the full list of exceptions to throw.
|
|
|
|
**Previous:** [Middleware](middleware.html)
|
|
|
|
**Next:** [Blueprints](blueprints.html)
|