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

doc: Improve errors documentation, esp. re serialization #1012

Merged
merged 2 commits into from
Apr 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 25 additions & 14 deletions docs/api/errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,28 @@
Error Handling
==============

When a request results in an error condition, you can manually set the
error status, appropriate response headers, and even an error body using the
``resp`` object. However, Falcon tries to make things a bit easier and more
consistent by providing a set of error classes you can raise from within
your app. Falcon catches any exception that inherits from
``falcon.HTTPError``, and automatically converts it to an appropriate HTTP
response.
When it comes to error handling, you can always directly set the error
status, appropriate response headers, and error body using the ``resp``
object. However, Falcon tries to make things a little easier by
providing a set of error classes you can raise when something goes
wrong. All of these classes inherit from :class:`~.HTTPError`.

Falcon will convert any instance or subclass of :class:`~.HTTPError`
raised by a responder, hook, or middleware component into an appropriate
HTTP response. The default error serializer supports both JSON and XML.
If the client indicates acceptance of both JSON and XML with equal
weight, JSON will be chosen. Other media types may be supported by
overriding the default serializer via
:meth:`~.API.set_error_serializer`.

.. note::

You may raise an instance of ``falcon.HTTPError`` directly, or use any one
of a number of predefined error classes that try to be idiomatic in
setting appropriate headers and bodies.
If a custom media type is used and the type includes a "+json" or
"+xml" suffix, the default serializer will convert the error to JSON
or XML, respectively.

All classes are available directly from the `falcon` package namespace::
Error classes are available directly from the `falcon` package
namespace::

import falcon

Expand All @@ -31,9 +40,11 @@ All classes are available directly from the `falcon` package namespace::

# ...

The default error serializer supports JSON and XML. You can override the
default serializer by passing a callable to the :class:`~.API` method,
:meth:`~.API.set_error_serializer`.
Note also that any exception (not just instances of
:class:`~.HTTPError`) can be caught, logged, and otherwise handled
at the global level by registering one or more custom error handlers.
See also :meth:`~.API.add_error_handler` to learn more about this
feature.

Base Class
----------
Expand Down
42 changes: 23 additions & 19 deletions falcon/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,13 @@ def add_sink(self, sink, prefix=r'/'):
def add_error_handler(self, exception, handler=None):
"""Registers a handler for a given exception error type.

A handler can raise an instance of ``HTTPError`` or
``HTTPStatus`` to communicate information about the issue to
Error handlers may be registered for any type, including
:class:`~.HTTPError`. This feature provides a central location
for logging and otherwise handling exceptions raised by
responders, hooks, and middleware components.

A handler can raise an instance of :class:`~.HTTPError` or
:class:`~.HTTPStatus` to communicate information about the issue to
the client. Alternatively, a handler may modify `resp`
directly.

Expand All @@ -438,8 +443,8 @@ def add_error_handler(self, exception, handler=None):
more than one handler matches the exception type, the framework
will choose the one that was most recently registered.
Therefore, more general error handlers (e.g., for the
``Exception`` type) should be added first, to avoid masking more
specific handlers for subclassed types.
standard ``Exception`` type) should be added first, to avoid
masking more specific handlers for subclassed types.

Args:
exception (type): Whenever an error occurs when handling a request
Expand Down Expand Up @@ -479,16 +484,22 @@ def handle(ex, req, resp, params):
self._error_handlers.insert(0, (exception, handler))

def set_error_serializer(self, serializer):
"""Override the default serializer for instances of HTTPError.
"""Override the default serializer for instances of :class:`~.HTTPError`.

When a responder raises an instance of :class:`~.HTTPError`,
Falcon converts it to an HTTP response automatically. The
default serializer supports JSON and XML, but may be overridden
by this method to use a custom serializer in order to support
other media types.

When a responder raises an instance of HTTPError, Falcon converts
it to an HTTP response automatically. The default serializer
supports JSON and XML, but may be overridden by this method to
use a custom serializer in order to support other media types.
Note:
If a custom media type is used and the type includes a
"+json" or "+xml" suffix, the default serializer will
convert the error to JSON or XML, respectively.

The ``falcon.HTTPError`` class contains helper methods, such as
`to_json()` and `to_dict()`, that can be used from within
custom serializers. For example::
The :class:`~.HTTPError` class contains helper methods,
such as `to_json()` and `to_dict()`, that can be used from
within custom serializers. For example::

def my_serializer(req, resp, exception):
representation = None
Expand All @@ -507,13 +518,6 @@ def my_serializer(req, resp, exception):

resp.append_header('Vary', 'Accept')

Note:
If a custom media type is used and the type includes a
"+json" or "+xml" suffix, the default serializer will
convert the error to JSON or XML, respectively. If this
is not desirable, a custom error serializer may be used
to override this behavior.

Args:
serializer (callable): A function taking the form
``func(req, resp, exception)``, where `req` is the request
Expand Down