Skip to content

Exceptions

API Reference: Exceptions

All public exceptions in SRF inherit from Sanic's HTTPException and are converted into JSON responses by Sanic. See Exceptions for usage.

from srf.exceptions import (
    ImproperlyConfigured,
    PydanticValidationException,
    TargetObjectAlreadyExist,
    TooManyRequest,
)

Exceptions at a glance

Exception Status code Typical trigger
TargetObjectAlreadyExist 409 A unique constraint is violated on create; it can also be raised explicitly in custom update logic
PydanticValidationException 422 Pydantic or Tortoise ValidationError
ImproperlyConfigured 500 An option has an invalid type (for example, INSTALLED_APPS is not a list)
TooManyRequest 429 Too many failed verification code attempts (for example, repeated confirmations on register)

TargetObjectAlreadyExist, PydanticValidationException and TooManyRequest set quiet = True, so Sanic does not log the corresponding request as an error.

Exception conversion in ViewSets

GenericAPIView.as_view() wraps view methods and performs the following conversions:

Original exception Conversion result
pydantic.ValidationError PydanticValidationException → 422
tortoise.exceptions.ValidationError PydanticValidationException → 422
tortoise.exceptions.IntegrityError CreateModelMixin.perform_create() converts it to TargetObjectAlreadyExist → 409

UpdateModelMixin.perform_update() does not catch IntegrityError itself; to turn unique constraint conflicts into 409, catch it in a subclass (see UserViewSet.perform_update) and raise TargetObjectAlreadyExist.

Sanic built-in exceptions such as NotFound, Forbidden, BadRequest, and MethodNotAllowed keep their original status codes and are not wrapped.

The response body is generated by Sanic's JSONRenderer:

{
  "description": "Unprocessable Entity",
  "status": 422,
  "message": "..."
}

Exception classes

TargetObjectAlreadyExist

Bases: HTTPException

When inserting data into the database, it already exists. You need to check the fields

status_code class-attribute instance-attribute

status_code = 409

quiet class-attribute instance-attribute

quiet = True

options: heading_level: 4 members: false show_source: false inherited_members: false

PydanticValidationException

Bases: HTTPException

The Pydantic validation error.

status_code class-attribute instance-attribute

status_code = 422

quiet class-attribute instance-attribute

quiet = True

options: heading_level: 4 members: false show_source: false inherited_members: false

ImproperlyConfigured

Bases: HTTPException

The system is improperly configured. Check your settings.

status_code class-attribute instance-attribute

status_code = 500

options: heading_level: 4 members: false show_source: false inherited_members: false

ImproperlyConfigured is mainly raised during LazySettings initialization: ALLOWED_HOSTS, INSTALLED_APPS, TEMPLATE_DIRS, LOCALE_PATHS, and SECRET_KEY_FALLBACKS must be lists or tuples.