Errors

Errors matter in the HTTP/RESTful ecosystem.

Clastic offers a full set of exception types representing standard HTTP errors, and a base HTTPException for creating your own exception types.

The errors module also contains the Error Handler subsystem for controlling how a Clastic Application behaves in error situations.

Error Handlers

You can control how Clastic responds to various error scenarios by creating or configuring an Error Handler and passing it to your Application instance.

Error Handlers are able to:

  • Control which specific error types are raised on routing failures (e.g., NotFound and MethodNotAllowed).
  • Control the error type which is raised when the endpoint or render function raises an uncaught exception (e.g., InternalServerError)
  • How uncaught exceptions are rendered or otherwise turned into HTTP Responses
  • Configure a WSGI middleware for the whole Application

The easiest way to control these behavior is to inherit from the default ErrorHandler and override the attributes or methods you need to change:

class clastic.errors.ErrorHandler(**kwargs)[source]

The default Clastic error handler. Provides minimal detail, suitable for a production setting.

Parameters:reraise_uncaught (bool) – Set to True if you want uncaught exceptions to be handled by the WSGI server rather than by this Clastic error handler.
exc_info_type

alias of boltons.tbutils.ExceptionInfo

method_not_allowed_type

alias of MethodNotAllowed

not_found_type

alias of NotFound

render_error(request, _error)[source]

Turn an HTTPException into a Response of your

Like endpoints and render functions, render_error() supports injection of any built-in arguments, as well as the _error argument (an instance of HTTPException, so feel free to adapt the signature as needed.

This method is attached to Routes as they are bound into Applications. Routes can technically override this behavior, but generally a Route’s error handling reflects that of the Error Handler in the root application where it is bound.

By default this method just adapts the response between text, HTML, XML, and JSON.

server_error_type

alias of InternalServerError

uncaught_to_response(_application, _route, **kwargs)[source]

Called in the except: block of Clastic’s routing. Must take the currently-being-handled exception and return a response instance. The default behavior returns an instance of whatever type is set in the server_error_type attribute (InternalServerError, by default).

Note that when inheriting, the method signature should accept **kwargs, as Clastic does not inject arguments as it does with endpoint functions, etc.

wsgi_wrapper = None

The default error handler presents the minimal detail to the client when an error occurs.

Clastic ships with a couple special Error Handlers which it uses to enable debuggability.

class clastic.errors.ContextualErrorHandler(*a, **kw)[source]

An error handler which offers a bit of debugging context, including a stack and locals (for server errors) and routes tried (for 404s).

Might be OK for some internal tools, but should generally not be used for production.

exc_info_type

alias of boltons.tbutils.ContextualExceptionInfo

not_found_type

alias of ContextualNotFound

server_error_type

alias of ContextualInternalServerError

class clastic.errors.REPLErrorHandler(*a, **kw)[source]

This error handler wraps the Application in a Werkzeug debug middleware.

The Base HTTPException

class clastic.HTTPException(detail=None, **kwargs)[source]

The base Exception for all default HTTP errors in this module, the HTTPException also inherits from BaseResponse, making instances of it and its subtypes valid to use via raising, as well as returning from endpoints and render functions.

Parameters:
  • detail (str) – A string with information about the exception. Appears in the body of the HTML error page.
  • code (int) – A numeric HTTP status code (e.g., 400 or 500).
  • message (str) – A short name for the error, (e.g., "Not Found")
  • error_type (str) – An error type name or link to a page with details about the type of error. Useful for linking to docs.
  • is_breaking (bool) – Advanced: For integrating with Clastic’s routing system, set to True to specify that this error instance should not preempt trying routes further down the routing table. If no other route matches or succeeds, this error will be raised.
  • source_route (Route) – Advanced: The route instance that raised this exception.
  • mimetype (str) – A MIME type to return in the Response headers.
  • content_type (str) – A Content-Type to return in the Response headers.
  • headers (dict) – A mapping of custom headers for the Response. Defaults to None.

Note

The base HTTPException includes simple serialization to text, HTML, XML, and JSON. So if a client requests a particular format (using the Accept header), it will automatically respond in that format. It defaults to text/plain if the requested MIME type is not recognized.

Standard HTTP Error Types

In addition to error handling mechanisms, clastic.error ships with exception types for every standard HTTP error.

Because these standard error types inherit from HTTPException, which is both an exception and a Response type, they can be raised or returned.

Errors are organized by error code, in ascending order. Note that the message attribute is sometimes called the “name”, e.g. “Not Found” for 404.

exception clastic.errors.BadRequest(detail=None, **kwargs)[source]
code = 400
detail = 'Your web client or proxy sent a request that this endpoint could not understand.'
message = 'Bad Request'
exception clastic.errors.Unauthorized(detail=None, **kwargs)[source]
code = 401
detail = 'The endpoint could not verify that your client is authorized to access this resource. Check that your client is capable of authenticating and that the proper credentials were provided.'
message = 'Authentication required'
exception clastic.errors.PaymentRequired(detail=None, **kwargs)[source]

HTTP cares about your paywall.

code = 402
detail = "This endpoint requires payment. Money doesn't grow on HTTPs, you know."
message = 'Payment required'
exception clastic.errors.Forbidden(detail=None, **kwargs)[source]
code = 403
detail = "You don't have permission to access the requested resource."
message = 'Access forbidden'
exception clastic.errors.ContextualNotFound(*a, **kw)[source]
to_dict()[source]

One design ideal, for showing which routes have been hit: [{‘route’: (‘pattern’, ‘endpoint’, ‘render_func’),

‘path_matched’: False, ‘method_matched’: False, ‘slash_matched’: False}]
to_html(*a, **kw)[source]
exception clastic.errors.MethodNotAllowed(allowed_methods=None, *args, **kwargs)[source]
code = 405
detail = 'The method used is not allowed for the requested URL.'
message = 'Method not allowed'
exception clastic.errors.NotAcceptable(detail=None, **kwargs)[source]
code = 406
detail = "The endpoint cannot generate a response acceptable by your client (as specified by your client's Accept header values)."
message = 'Available content not acceptable'
exception clastic.errors.ProxyAuthenticationRequired(detail=None, **kwargs)[source]
code = 407
detail = 'A proxy between your server and the client requires authentication to access this resource.'
message = 'Proxy authentication required'
exception clastic.errors.RequestTimeout(detail=None, **kwargs)[source]
code = 408
detail = 'The server cancelled the request because the client did not complete the request within the alotted time.'
message = 'Request timed out'
exception clastic.errors.Conflict(detail=None, **kwargs)[source]
code = 409
detail = 'The endpoint cancelled the request due to a potential conflict with existing server state, such as a duplicate filename.'
message = 'A conflict occurred'
exception clastic.errors.Gone(detail=None, **kwargs)[source]
code = 410
detail = 'The requested resource is no longer available on this server and there is no forwarding address.'
message = 'Gone'
exception clastic.errors.LengthRequired(detail=None, **kwargs)[source]
code = 411
detail = 'A request for this resource is required to have a valid Content-Length header.'
message = 'Length required'
exception clastic.errors.PreconditionFailed(detail=None, **kwargs)[source]
code = 412
detail = 'A required precondition on the request for this resource failed positive evaluation.'
message = 'Precondition failed'
exception clastic.errors.RequestEntityTooLarge(detail=None, **kwargs)[source]
code = 413
detail = 'The method/resource combination requested does not allow data to be transmitted, or the data volume exceeds the capacity limit.'
message = 'Request entity too large'
exception clastic.errors.RequestURITooLong(detail=None, **kwargs)[source]
code = 414
detail = 'The length of the requested URL exceeds the limit for this endpoint/server.'
message = 'Request URL too long'
exception clastic.errors.UnsupportedMediaType(detail=None, **kwargs)[source]
code = 415
detail = 'The server does not support the media type transmitted in the request. Try a different media type or check your Content-Type header and try again.'
message = 'Unsupported media type'
exception clastic.errors.RequestedRangeNotSatisfiable(detail=None, **kwargs)[source]
code = 416
detail = 'The client sent a ranged request not fulfillable by this endpoint.'
message = 'Requested range not satisfiable'
exception clastic.errors.ExpectationFailed(detail=None, **kwargs)[source]

Can’t. always. get. what you want.

code = 417
detail = "The server could not meet the requirements indicated in the request's Expect header(s)."
message = 'Expectation failed'
exception clastic.errors.ImATeapot(detail=None, **kwargs)[source]

Standards committees are known for their senses of humor.

code = 418
detail = 'This server is a teapot, not a coffee machine, and would like to apologize in advance if it is a Java machine.'
message = "I'm a teapot: short, stout."
exception clastic.errors.UnprocessableEntity(detail=None, **kwargs)[source]
code = 422
detail = 'The client sent a well-formed request, but the endpoint encountered other semantic errors within the data.'
message = 'Unprocessable entity'
exception clastic.errors.UpgradeRequired(detail=None, **kwargs)[source]

Used to upgrade connections (to TLS, etc., RFC2817). Also WebSockets.

code = 426
detail = 'The server requires an upgraded connection to continue. This is expected behavior when establishing certain secure connections or WebSockets.'
message = 'Upgrade required'
exception clastic.errors.PreconditionRequired(detail=None, **kwargs)[source]
code = 428
detail = "This endpoint requires a request with a conditional clause. Try resubmitting the request with an 'If-Match' or 'If-Unmodified-Since' HTTP header."
message = 'Precondition required'
exception clastic.errors.TooManyRequests(detail=None, **kwargs)[source]
code = 429
detail = 'The client has exceeded the allowed rate of requests for this resource. Please wait and try again later.'
message = 'Too many requests'
exception clastic.errors.RequestHeaderFieldsTooLarge(detail=None, **kwargs)[source]
code = 431
detail = 'One or more HTTP header fields exceeded the maximum allowed size.'
message = 'Request header fields too large'
exception clastic.errors.UnavailableForLegalReasons(detail=None, **kwargs)[source]

Sit back and enjoy the Bradbury

code = 451
detail = 'The resource requested is unavailable for legal reasons. For instance, this could be due to intellectual property claims related to copyright or trademark, or government-mandated censorship.'
message = 'Unavailable for legal reasons'
exception clastic.errors.ContextualInternalServerError(*a, **kw)[source]

An Internal Server Error with a full contextual view of the exception, mostly for development (non-production) purposes.

# NOTE: The dict returned by to_dict is not JSON-encodable with the default encoder. It relies on the ClasticJSONEncoder currently used in the InternalServerError class.

to_dict(*a, **kw)[source]
to_html(*a, **kw)[source]
exception clastic.errors.NotImplemented(detail=None, **kwargs)[source]
code = 501
detail = 'The resource requested has either not been implemented or does not yet support the action requested by the client.'
message = 'Response behavior not implemented'
exception clastic.errors.BadGateway(detail=None, **kwargs)[source]
code = 502
detail = 'The endpoint received an invalid response from an upstream server while processing your request. Check that all upstream dependencies are properly configured and running.'
message = 'Bad gateway'
exception clastic.errors.ServiceUnavailable(detail=None, **kwargs)[source]
code = 503
detail = 'The service or resource requested is temporarily unavailable due to maintenance downtime or capacity issues. Please try again later.'
message = 'Service or resource unavailable'
exception clastic.errors.GatewayTimeout(detail=None, **kwargs)[source]
code = 504
detail = 'The endpoint timed out while waiting for a response from an upstream server. check that all upstream dependencies are properly configured and running.'
message = 'Gateway timeout'
exception clastic.errors.HTTPVersionNotSupported(detail=None, **kwargs)[source]
code = 505
detail = 'The endpoint does not support the version of HTTP specified by the request.'
message = 'HTTP version not supported'