HTTP Exceptions¶
Implements a number of Python exceptions which can be raised from within a view to trigger a standard HTTP non-200 response.
Usage Example¶
from werkzeug.wrappers.request import Request
from werkzeug.exceptions import HTTPException, NotFound
def view(request):
raise NotFound()
@Request.application
def application(request):
try:
return view(request)
except HTTPException as e:
return e
As you can see from this example those exceptions are callable WSGI
applications. However, they are not Werkzeug response objects. You
can get a response object by calling get_response()
on a HTTP
exception.
Keep in mind that you may have to pass an environ (WSGI) or scope
(ASGI) to get_response()
because some errors fetch additional
information relating to the request.
If you want to hook in a different exception page to say, a 404 status code, you can add a second except for a specific subclass of an error:
@Request.application
def application(request):
try:
return view(request)
except NotFound as e:
return not_found(request)
except HTTPException as e:
return e
Error Classes¶
The following error classes exist in Werkzeug:
- exception werkzeug.exceptions.BadRequest(description=None, response=None)¶
400
Bad Request
Raise if the browser sends something to the application the application or server cannot handle.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.Unauthorized(description=None, response=None, www_authenticate=None)¶
401
Unauthorized
Raise if the user is not authorized to access a resource.
The
www_authenticate
argument should be used to set theWWW-Authenticate
header. This is used for HTTP basic auth and other schemes. UseWWWAuthenticate
to create correctly formatted values. Strictly speaking a 401 response is invalid if it doesn’t provide at least one value for this header, although real clients typically don’t care.- Parameters:
description (str | None) – Override the default message used for the body of the response.
www-authenticate – A single value, or list of values, for the WWW-Authenticate header(s).
response (Response | None)
www_authenticate (None | (WWWAuthenticate | t.Iterable[WWWAuthenticate]))
- Return type:
None
Changelog
Changed in version 2.0: Serialize multiple
www_authenticate
items into multipleWWW-Authenticate
headers, rather than joining them into a single value, for better interoperability.Changed in version 0.15.3: If the
www_authenticate
argument is not set, theWWW-Authenticate
header is not set.Changed in version 0.15.3: The
response
argument was restored.Changed in version 0.15.1:
description
was moved back as the first argument, restoring its previous position.Changed in version 0.15.0:
www_authenticate
was added as the first argument, ahead ofdescription
.
- exception werkzeug.exceptions.Forbidden(description=None, response=None)¶
403
Forbidden
Raise if the user doesn’t have the permission for the requested resource but was authenticated.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.NotFound(description=None, response=None)¶
404
Not Found
Raise if a resource does not exist and never existed.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.MethodNotAllowed(valid_methods=None, description=None, response=None)¶
405
Method Not Allowed
Raise if the server used a method the resource does not handle. For example
POST
if the resource is view only. Especially useful for REST.The first argument for this exception should be a list of allowed methods. Strictly speaking the response would be invalid if you don’t provide valid methods in the header which you can do with that list.
Takes an optional list of valid http methods starting with werkzeug 0.3 the list will be mandatory.
- Parameters:
valid_methods (t.Iterable[str] | None)
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.NotAcceptable(description=None, response=None)¶
406
Not Acceptable
Raise if the server can’t return any content conforming to the
Accept
headers of the client.- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.RequestTimeout(description=None, response=None)¶
408
Request Timeout
Raise to signalize a timeout.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.Conflict(description=None, response=None)¶
409
Conflict
Raise to signal that a request cannot be completed because it conflicts with the current state on the server.
Changelog
Added in version 0.7.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.Gone(description=None, response=None)¶
410
Gone
Raise if a resource existed previously and went away without new location.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.LengthRequired(description=None, response=None)¶
411
Length Required
Raise if the browser submitted data but no
Content-Length
header which is required for the kind of processing the server does.- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.PreconditionFailed(description=None, response=None)¶
412
Precondition Failed
Status code used in combination with
If-Match
,If-None-Match
, orIf-Unmodified-Since
.- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.RequestEntityTooLarge(description=None, response=None)¶
413
Request Entity Too Large
The status code one should return if the data submitted exceeded a given limit.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.RequestURITooLarge(description=None, response=None)¶
414
Request URI Too Large
Like 413 but for too long URLs.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.UnsupportedMediaType(description=None, response=None)¶
415
Unsupported Media Type
The status code returned if the server is unable to handle the media type the client transmitted.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.RequestedRangeNotSatisfiable(length=None, units='bytes', description=None, response=None)¶
416
Requested Range Not Satisfiable
The client asked for an invalid part of the file.
Changelog
Added in version 0.7.
Takes an optional
Content-Range
header value based onlength
parameter.- Parameters:
length (int | None)
units (str)
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.ExpectationFailed(description=None, response=None)¶
417
Expectation Failed
The server cannot meet the requirements of the Expect request-header.
Changelog
Added in version 0.7.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.ImATeapot(description=None, response=None)¶
418
I'm a teapot
The server should return this if it is a teapot and someone attempted to brew coffee with it.
Changelog
Added in version 0.7.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.UnprocessableEntity(description=None, response=None)¶
422
Unprocessable Entity
Used if the request is well formed, but the instructions are otherwise incorrect.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.Locked(description=None, response=None)¶
423
Locked
Used if the resource that is being accessed is locked.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.FailedDependency(description=None, response=None)¶
424
Failed Dependency
Used if the method could not be performed on the resource because the requested action depended on another action and that action failed.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.PreconditionRequired(description=None, response=None)¶
428
Precondition Required
The server requires this request to be conditional, typically to prevent the lost update problem, which is a race condition between two or more clients attempting to update a resource through PUT or DELETE. By requiring each client to include a conditional header (“If-Match” or “If-Unmodified- Since”) with the proper value retained from a recent GET request, the server ensures that each client has at least seen the previous revision of the resource.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.TooManyRequests(description=None, response=None, retry_after=None)¶
429
Too Many Requests
The server is limiting the rate at which this user receives responses, and this request exceeds that rate. (The server may use any convenient method to identify users and their request rates). The server may include a “Retry-After” header to indicate how long the user should wait before retrying.
- Parameters:
retry_after (datetime | int | None) – If given, set the
Retry-After
header to this value. May be anint
number of seconds or adatetime
.description (str | None)
response (Response | None)
- Return type:
None
Changelog
Changed in version 1.0: Added
retry_after
parameter.
- exception werkzeug.exceptions.RequestHeaderFieldsTooLarge(description=None, response=None)¶
431
Request Header Fields Too Large
The server refuses to process the request because the header fields are too large. One or more individual fields may be too large, or the set of all headers is too large.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
451
Unavailable For Legal Reasons
This status code indicates that the server is denying access to the resource as a consequence of a legal demand.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.InternalServerError(description=None, response=None, original_exception=None)¶
500
Internal Server Error
Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher.
Changelog
Changed in version 1.0.0: Added the
original_exception
attribute.- Parameters:
description (str | None)
response (Response | None)
original_exception (BaseException | None)
- Return type:
None
- original_exception¶
The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors.
- exception werkzeug.exceptions.NotImplemented(description=None, response=None)¶
501
Not Implemented
Raise if the application does not support the action requested by the browser.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.BadGateway(description=None, response=None)¶
502
Bad Gateway
If you do proxying in your application you should return this status code if you received an invalid response from the upstream server it accessed in attempting to fulfill the request.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
503
Service Unavailable
Status code you should return if a service is temporarily unavailable.
- Parameters:
retry_after (datetime | int | None) – If given, set the
Retry-After
header to this value. May be anint
number of seconds or adatetime
.description (str | None)
response (Response | None)
- Return type:
None
Changelog
Changed in version 1.0: Added
retry_after
parameter.
- exception werkzeug.exceptions.GatewayTimeout(description=None, response=None)¶
504
Gateway Timeout
Status code you should return if a connection to an upstream server times out.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.HTTPVersionNotSupported(description=None, response=None)¶
505
HTTP Version Not Supported
The server does not support the HTTP protocol version used in the request.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- exception werkzeug.exceptions.ClientDisconnected(description=None, response=None)¶
Internal exception that is raised if Werkzeug detects a disconnected client. Since the client is already gone at that point attempting to send the error message to the client might not work and might ultimately result in another exception in the server. Mainly this is here so that it is silenced by default as far as Werkzeug is concerned.
Since disconnections cannot be reliably detected and are unspecified by WSGI to a large extent this might or might not be raised if a client is gone.
Changelog
Added in version 0.8.
- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
Baseclass¶
All the exceptions implement this common interface:
- exception werkzeug.exceptions.HTTPException(description=None, response=None)¶
The base class for all HTTP exceptions. This exception can be called as a WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages.
Changelog
Changed in version 2.1: Removed the
wrap
class method.- Parameters:
description (str | None)
response (Response | None)
- Return type:
None
- get_response(environ=None, scope=None)¶
Get a response object. If one was passed to the exception it’s returned directly.
- Parameters:
environ (WSGIEnvironment | WSGIRequest | None) – the optional environ for the request. This can be used to modify the response depending on how the request looked like.
scope (dict[str, t.Any] | None)
- Returns:
a
Response
object or a subclass thereof.- Return type:
- __call__(environ, start_response)¶
Call the exception as WSGI application.
- Parameters:
environ (WSGIEnvironment) – the WSGI environment.
start_response (StartResponse) – the response callable provided by the WSGI server.
- Return type:
t.Iterable[bytes]
Special HTTP Exceptions¶
Starting with Werkzeug 0.3 some of the builtin classes raise exceptions that
look like regular python exceptions (eg KeyError
) but are
BadRequest
HTTP exceptions at the same time. This decision was made
to simplify a common pattern where you want to abort if the client tampered
with the submitted form data in a way that the application can’t recover
properly and should abort with 400 BAD REQUEST
.
Assuming the application catches all HTTP exceptions and reacts to them properly a view function could do the following safely and doesn’t have to check if the keys exist:
def new_post(request):
post = Post(title=request.form['title'], body=request.form['body'])
post.save()
return redirect(post.url)
If title
or body
are missing in the form, a special key error will be
raised which behaves like a KeyError
but also a BadRequest
exception.
- exception werkzeug.exceptions.BadRequestKeyError(arg=None, *args, **kwargs)¶
An exception that is used to signal both a
KeyError
and aBadRequest
. Used by many of the datastructures.- Parameters:
arg (str | None)
args (t.Any)
kwargs (t.Any)
Simple Aborting¶
Sometimes it’s convenient to just raise an exception by the error code,
without importing the exception and looking up the name etc. For this
purpose there is the abort()
function.
- werkzeug.exceptions.abort(status, *args, **kwargs)¶
Raises an
HTTPException
for the given status code or WSGI application.If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:
abort(404) # 404 Not Found abort(Response('Hello World'))
- Parameters:
status (int | Response)
args (t.Any)
kwargs (t.Any)
- Return type:
t.NoReturn
If you want to use this functionality with custom exceptions you can create an instance of the aborter class:
- class werkzeug.exceptions.Aborter(mapping=None, extra=None)¶
When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception.
The rest of the arguments are forwarded to the exception constructor.
- Parameters:
mapping (dict[int, type[HTTPException]] | None)
extra (dict[int, type[HTTPException]] | None)
Custom Errors¶
As you can see from the list above not all status codes are available as
errors. Especially redirects and other non 200 status codes that do not
represent errors are missing. For redirects you can use the redirect()
function from the utilities.
If you want to add an error yourself you can subclass HTTPException
:
from werkzeug.exceptions import HTTPException
class PaymentRequired(HTTPException):
code = 402
description = '<p>Payment required.</p>'
This is the minimal code you need for your own exception. If you want to
add more logic to the errors you can override the
get_description()
, get_body()
,
get_headers()
and get_response()
methods. In any case you should have a look at the sourcecode of the
exceptions module.
You can override the default description in the constructor with the
description
parameter:
raise BadRequest(description='Request failed because X was not present')