Exceptions

sanic.errorpages

Sanic provides a pattern for providing a response when an exception occurs. However, if you do no handle an exception, it will provide a fallback. There are three fallback types:

  • HTML - default

  • Text

  • JSON

Setting app.config.FALLBACK_ERROR_FORMAT = "auto" will enable a switch that will attempt to provide an appropriate response format based upon the request type.

class sanic.errorpages.BaseRenderer(request, exception, debug)

Bases: object

Base class that all renderers must inherit from.

static dumps()

Converts arbitrary object recursively into JSON. Use ensure_ascii=false to output UTF-8. Set encode_html_chars=True to encode < > & as unicode escape sequences. Set escape_forward_slashes=False to prevent escaping / characters.Set allow_nan=False to raise an exception when NaN or Infinity would be serialized.Set reject_bytes=True to raise TypeError on bytes.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type:

HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type:

HTTPResponse

render()

Outputs the exception as a HTTPResponse.

Returns:

The formatted exception

Return type:

str

class sanic.errorpages.HTMLRenderer(request, exception, debug)

Bases: BaseRenderer

Render an exception as HTML.

The default fallback type.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type:

HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type:

HTTPResponse

class sanic.errorpages.JSONRenderer(request, exception, debug)

Bases: BaseRenderer

Render an exception as JSON.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type:

HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type:

HTTPResponse

class sanic.errorpages.TextRenderer(request, exception, debug)

Bases: BaseRenderer

Render an exception as plain text.

full()

Provide a formatted message that has all details and is mean to be used primarily for debugging and non-production environments.

Return type:

HTTPResponse

minimal()

Provide a formatted message that is meant to not show any sensitive data or details.

Return type:

HTTPResponse

sanic.errorpages.escape(text)

Minimal HTML escaping, not for attribute values (unlike html.escape).

sanic.errorpages.exception_response(request, exception, debug, fallback, base, renderer=None)

Render a response for the default FALLBACK exception handler.

Parameters:
  • request (Request) –

  • exception (Exception) –

  • debug (bool) –

  • fallback (str) –

  • base (t.Type[BaseRenderer]) –

  • renderer (t.Type[t.Optional[BaseRenderer]]) –

Return type:

HTTPResponse

sanic.exceptions

exception sanic.exceptions.BadRequest(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 400 Bad Request

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Bad Request’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

sanic.exceptions.BadURL

alias of BadRequest

sanic.exceptions.ContentRangeError

alias of RangeNotSatisfiable

exception sanic.exceptions.ExpectationFailed(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 417 Expectation Failed

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Expectation Failed’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.FileNotFound(message=None, path=None, relative_url=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: NotFound

Status: 404 Not Found

A specific form of NotFound that is specifically when looking for a file on the file system at a known path.

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Not Found’ will be sent, defaults to None

  • path (Optional[PathLike], optional) – The path, if any, to the file that could not be found, defaults to None

  • relative_url (Optional[str], optional) – A relative URL of the file, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

exception sanic.exceptions.Forbidden(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 403 Forbidden

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Forbidden’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.HTTPException(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: SanicException

A base class for other exceptions and should not be called directly.

Parameters:
  • message (str) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

sanic.exceptions.HeaderExpectationFailed

alias of ExpectationFailed

exception sanic.exceptions.HeaderNotFound(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: BadRequest

Status: 400 Bad Request

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Bad Request’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

sanic.exceptions.InternalServerError

alias of ServerError

exception sanic.exceptions.InvalidHeader(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: BadRequest

Status: 400 Bad Request

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Bad Request’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.InvalidRangeType(message=None, content_range=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: RangeNotSatisfiable

Status: 416 Range Not Satisfiable

Parameters:
  • message (str) –

  • content_range (ContentRange | None) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

exception sanic.exceptions.InvalidSignal(message=None, status_code=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: SanicException

Parameters:
  • message (str) –

  • status_code (int) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

sanic.exceptions.InvalidUsage

alias of BadRequest

exception sanic.exceptions.LoadFileException(message=None, status_code=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: SanicException

Parameters:
  • message (str) –

  • status_code (int) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

exception sanic.exceptions.MethodNotAllowed(message=None, method='', allowed_methods=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 405 Method Not Allowed

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Method Not Allowed’ will be sent, defaults to None

  • method (Optional[str], optional) – The HTTP method that was used, defaults to an empty string

  • allowed_methods (Optional[Sequence[str]], optional) – The HTTP methods that can be used instead of the one that was attempted

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

sanic.exceptions.MethodNotSupported

alias of MethodNotAllowed

exception sanic.exceptions.NotFound(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 404 Not Found

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Not Found’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.PayloadTooLarge(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 413 Payload Too Large

This is an internal exception thrown by Sanic and should not be used directly.

Parameters:
  • message (str) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

exception sanic.exceptions.PyFileError(file, status_code=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: SanicException

Parameters:
  • status_code (int) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

exception sanic.exceptions.RangeNotSatisfiable(message=None, content_range=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 416 Range Not Satisfiable

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Range Not Satisfiable’ will be sent, defaults to None

  • content_range (Optional[ContentRange], optional) – An object meeting the ContentRange protocol that has a total property, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

exception sanic.exceptions.RequestCancelled

Bases: CancelledError

exception sanic.exceptions.RequestTimeout(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

The Web server (running the Web site) thinks that there has been too long an interval of time between 1) the establishment of an IP connection (socket) between the client and the server and 2) the receipt of any data on that socket, so the server has dropped the connection. The socket connection has actually been lost - the Web server has β€˜timed out’ on that particular socket connection.

This is an internal exception thrown by Sanic and should not be used directly.

Parameters:
  • message (str) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

exception sanic.exceptions.SanicException(message=None, status_code=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: Exception

Generic exception that will generate an HTTP response when raised in the context of a request lifecycle.

Usually it is best practice to use one of the more specific exceptions than this generic. Even when trying to raise a 500, it is generally preferrable to use ServerError

raise SanicException(
    "Something went wrong",
    status_code=999,
    context={
        "info": "Some additional details",
    },
    headers={
        "X-Foo": "bar"
    }
)
Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the appropriate HTTP response status message will be used instead, defaults to None

  • status_code (Optional[int], optional) – The HTTP response code to send, if applicable. If None, then it will be 500, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.ServerError(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 500 Internal Server Error

A general server-side error has occurred. If no other HTTP exception is appropriate, then this should be used

Parameters:
  • message (Optional[Union[str, bytes]], optional) –

    The message to be sent to the client. If None then the HTTP status β€˜Internal Server Error’ will be sent,

    defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.ServerKilled

Bases: Exception

Exception Sanic server uses when killing a server process for something unexpected happening.

exception sanic.exceptions.ServiceUnavailable(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 503 Service Unavailable

The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Bad Request’ will be sent, defaults to None

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

Return type:

None

exception sanic.exceptions.URLBuildError(message=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: HTTPException

Status: 500 Internal Server Error

An exception used by Sanic internals when unable to build a URL.

Parameters:
  • message (str) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

exception sanic.exceptions.Unauthorized(message=None, scheme=None, *, quiet=None, context=None, extra=None, headers=None, **challenges)

Bases: HTTPException

Status: 401 Unauthorized

When present, additional keyword arguments may be used to complete the WWW-Authentication header.

Examples:

# With a Basic auth-scheme, realm MUST be present:
raise Unauthorized("Auth required.",
                   scheme="Basic",
                   realm="Restricted Area")

# With a Digest auth-scheme, things are a bit more complicated:
raise Unauthorized("Auth required.",
                   scheme="Digest",
                   realm="Restricted Area",
                   qop="auth, auth-int",
                   algorithm="MD5",
                   nonce="abcdef",
                   opaque="zyxwvu")

# With a Bearer auth-scheme, realm is optional so you can write:
raise Unauthorized("Auth required.", scheme="Bearer")

# or, if you want to specify the realm:
raise Unauthorized("Auth required.",
                   scheme="Bearer",
                   realm="Restricted Area")
Parameters:
  • message (Optional[Union[str, bytes]], optional) – The message to be sent to the client. If None then the HTTP status β€˜Bad Request’ will be sent, defaults to None

  • scheme (Optional[str], optional) – Name of the authentication scheme to be used.

  • quiet (Optional[bool], optional) – When True, the error traceback will be suppressed from the logs, defaults to None

  • context (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will be sent to the client upon exception, defaults to None

  • extra (Optional[Dict[str, Any]], optional) – Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode, defaults to None

  • headers (Optional[Dict[str, Any]], optional) – Additional headers that should be sent with the HTTP response, defaults to None

exception sanic.exceptions.WebsocketClosed(message=None, status_code=None, *, quiet=None, context=None, extra=None, headers=None)

Bases: SanicException

Parameters:
  • message (str) –

  • status_code (int) –

  • quiet (bool | None) –

  • context (Dict[str, Any] | None) –

  • extra (Dict[str, Any] | None) –

  • headers (Dict[str, str]) –

Return type:

None

class sanic.exceptions.ContentRange

Bases: Protocol