Error Handling

When a request results in an error condition, you could 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.

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.

Base Class

class falcon.HTTPError(status, title=None, description=None, headers=None, href=None, href_text=None, code=None)[source]

Represents a generic HTTP error.

Raise this or a child class to have Falcon automagically return pretty error responses (with an appropriate HTTP status code) to the client when something goes wrong.

status

str – HTTP status line, e.g. ‘748 Confounded by Ponies’.

has_representation

bool – Read-only property that determines whether error details will be serialized when composing the HTTP response. In HTTPError this property always returns True, but child classes may override it in order to return False when an empty HTTP body is desired. See also the falcon.http_error.NoRepresentation mixin.

title

str – Error title to send to the client. Will be None if the error should result in an HTTP response with an empty body.

description

str – Description of the error to send to the client.

headers

dict – Extra headers to add to the response.

str – An href that the client can provide to the user for getting help.

code

int – An internal application code that a user can reference when requesting support for the error.

Parameters:

status (str) – HTTP status code and text, such as “400 Bad Request”

Keyword Arguments:
 
  • title (str) – Human-friendly error title (default None).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two (default None).
  • headers (dict) –

    A dict of header names and values to set, or a list of (name, value) tuples. Both name and value must be of type str or StringType, and only character values 0x00 through 0xFF may be used on platforms that use wide characters.

    Note

    The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client

    Note

    Falcon can process a list of tuple slightly faster than a dict.

  • headers – Extra headers to return in the response to the client (default None).
  • href (str) – A URL someone can visit to find out more information (default None). Unicode characters are percent-encoded.
  • href_text (str) – If href is given, use this as the friendly title/description for the link (defaults to “API documentation for this error”).
  • code (int) – An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default None).
to_dict(obj_type=<type 'dict'>)[source]

Returns a basic dictionary representing the error.

This method can be useful when serializing the error to hash-like media types, such as YAML, JSON, and MessagePack.

Parameters:obj_type – A dict-like type that will be used to store the error information (default dict).
Returns:A dictionary populated with the error’s title, description, etc.
to_json()[source]

Returns a pretty-printed JSON representation of the error.

Returns:A JSON document for the error.
to_xml()[source]

Returns an XML-encoded representation of the error.

Returns:An XML document for the error.

Mixins

class falcon.http_error.NoRepresentation[source]

Mixin for HTTPError child classes that have no representation.

This class can be mixed in when inheriting from HTTPError, in order to override the has_representation property such that it always returns False. This, in turn, will cause Falcon to return an empty response body to the client.

You can use this mixin when defining errors that either should not have a body (as dictated by HTTP standards or common practice), or in the case that a detailed error response may leak information to an attacker.

Note

This mixin class must appear before HTTPError in the base class list when defining the child; otherwise, it will not override the has_representation property as expected.

Predefined Errors

exception falcon.HTTPInvalidHeader(msg, header_name, **kwargs)[source]

HTTP header is invalid. Inherits from HTTPBadRequest.

Parameters:
  • msg (str) – A description of why the value is invalid.
  • header_name (str) – The name of the header.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPMissingHeader(header_name, **kwargs)[source]

HTTP header is missing. Inherits from HTTPBadRequest.

Parameters:
  • header_name (str) – The name of the header.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPInvalidParam(msg, param_name, **kwargs)[source]

HTTP parameter is invalid. Inherits from HTTPBadRequest.

Parameters:
  • msg (str) – A description of the invalid parameter.
  • param_name (str) – The name of the paramameter.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPMissingParam(param_name, **kwargs)[source]

HTTP parameter is missing. Inherits from HTTPBadRequest.

Parameters:
  • param_name (str) – The name of the paramameter.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPBadRequest(title, description, **kwargs)[source]

400 Bad Request.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. (RFC 2616)

Parameters:
  • title (str) – Error title (e.g., ‘TTL Out of Range’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPUnauthorized(title, description, **kwargs)[source]

401 Unauthorized.

Use when authentication is required, and the provided credentials are not valid, or no credentials were provided in the first place.

Parameters:
  • title (str) – Error title (e.g., ‘Authentication Required’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • scheme (str) – Authentication scheme to use as the value of the WWW-Authenticate header in the response (default None).
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPForbidden(title, description, **kwargs)[source]

403 Forbidden.

Use when the client’s credentials are good, but they do not have permission to access the requested resource.

If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead. (RFC 2616)

Parameters:
  • title (str) – Error title (e.g., ‘Permission Denied’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPNotFound(**kwargs)[source]

404 Not Found.

Use this when the URL path does not map to an existing resource, or you do not wish to disclose exactly why a request was refused.

exception falcon.HTTPMethodNotAllowed(allowed_methods, **kwargs)[source]

405 Method Not Allowed.

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. (RFC 2616)

Parameters:allowed_methods (list of str) – Allowed HTTP methods for this resource (e.g., ['GET', 'POST', 'HEAD']).
exception falcon.HTTPNotAcceptable(description, **kwargs)[source]

406 Not Acceptable.

The client requested a resource in a representation that is not supported by the server. The client must indicate a supported media type in the Accept header.

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request. (RFC 2616)

Parameters:
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPConflict(title, description, **kwargs)[source]

409 Conflict.

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

(RFC 2616)

Parameters:
  • title (str) – Error title (e.g., ‘Editing Conflict’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPLengthRequired(title, description, **kwargs)[source]

411 Length Required.

The server refuses to accept the request without a defined Content-Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message. (RFC 2616)

Parameters:
  • title (str) – Error title (e.g., ‘Missing Content-Length’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPPreconditionFailed(title, description, **kwargs)[source]

412 Precondition Failed.

The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended. (RFC 2616)

Parameters:
  • title (str) – Error title (e.g., ‘Image Not Modified’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPUnsupportedMediaType(description, **kwargs)[source]

415 Unsupported Media Type.

The client is trying to submit a resource encoded as an Internet media type that the server does not support.

Parameters:
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPRangeNotSatisfiable(resource_length)[source]

416 Range Not Satisfiable.

The requested range is not valid. See also: http://goo.gl/Qsa4EF

Parameters:resource_length – The maximum value for the last-byte-pos of a range request. Used to set the Content-Range header.
exception falcon.HTTPInternalServerError(title, description, **kwargs)[source]

500 Internal Server Error.

Parameters:
  • title (str) – Error title (e.g., ‘This Should Never Happen’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPBadGateway(title, description, **kwargs)[source]

502 Bad Gateway.

Parameters:
  • title (str) – Error title, for example: ‘Upstream Server is Unavailable’.
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • kwargs (optional) – Same as for HTTPError.
exception falcon.HTTPServiceUnavailable(title, description, retry_after, **kwargs)[source]

503 Service Unavailable.

Parameters:
  • title (str) – Error title (e.g., ‘Temporarily Unavailable’).
  • description (str) – Human-friendly description of the error, along with a helpful suggestion or two.
  • retry_after (datetime or int) – Value for the Retry-After header. If a datetime object, will serialize as an HTTP date. Otherwise, a non-negative int is expected, representing the number of seconds to wait. See also: http://goo.gl/DIrWr .
  • kwargs (optional) – Same as for HTTPError.