Exceptions¶
Utilities for converting application exceptions into DRF exceptions and formatting error responses.
map_to_drf_exception¶
Convert an application exception into the closest DRF exception.
The exception must expose the following attributes:
| Attribute | Description |
|---|---|
http_status |
HTTP status code |
message |
Human-readable error message |
error_code |
Machine-readable error code |
Example:
class UserNotFound(Exception):
http_status = 404
error_code = "user_not_found"
def __init__(self):
self.message = "User not found"
ExceptionFormatter¶
Formats errors generated by drf-standardized-errors into the
drf-corekit response structure.
Example:
{
"data": null,
"type": "validation_error",
"errors": [
{
"code": "required",
"message": "This field is required.",
"param": "email"
}
]
}
Exception Classes¶
BaseException¶
The root class for all client facing application exceptions. Defaults to a 400 Bad Request response.
| Attribute | Default |
|---|---|
http_status |
HTTP_400_BAD_REQUEST |
error_code |
"generic_error" |
class PaymentRequiredException(BaseException):
http_status = rest_status.HTTP_402_PAYMENT_REQUIRED
error_code = "payment_required"
Note
Subclasses only need to override the attributes they want to change —
http_status, error_code, or both. The message argument defaults
to the class name if omitted.
BaseServerException¶
Base class for internal server-side exceptions. Defaults to a 500 Internal Server Error response. Use this for infrastructure failures, third-party service errors, or anything the client cannot be expected to recover from.
| Attribute | Default |
|---|---|
http_status |
HTTP_500_INTERNAL_SERVER_ERROR |
error_code |
"server_error" |
PermissionDenied¶
Raised when an authenticated user attempts an action they are not authorised to perform. Returns a 403 Forbidden response.
| Attribute | Value |
|---|---|
http_status |
HTTP_403_FORBIDDEN |
error_code |
"permission_denied" |
The default message is the translated string:
Override it at the call site for context-specific messaging: