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:
Exception classes¶
TargetObjectAlreadyExist ¶
options: heading_level: 4 members: false show_source: false inherited_members: false
PydanticValidationException ¶
options: heading_level: 4 members: false show_source: false inherited_members: false
ImproperlyConfigured ¶
Bases: HTTPException
The system is improperly configured. Check your settings.
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.