Skip to content

Exceptions

Utilities for converting application exceptions into DRF exceptions and formatting error responses.

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

AppException

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(AppException):
    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, default_message, or any of them. The message argument defaults to default_message ("Something went wrong." on AppException) if omitted. error_code can also be set per call: NotFoundException("No invoice.", error_code="invoice_not_found").

ServerErrorException

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"
class DatabaseUnavailableException(ServerErrorException):
    error_code = "database_unavailable"

PermissionDeniedException

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:

"You do not have permission to perform this action."

Override it at the call site for context-specific messaging:

raise PermissionDeniedException("Only organisation admins can delete members.")

NotFoundException

Raised when a requested resource does not exist. Returns a 404 Not Found response.

Attribute Value
http_status HTTP_404_NOT_FOUND
error_code "not_found"

ConflictException

Raised when the request cannot be done because of the current state of the resource, such as a duplicate or a record that is still in use. Returns a 409 Conflict response.

Attribute Value
http_status HTTP_409_CONFLICT
error_code "conflict"
class ClientHasInvoices(ConflictException):
    error_code = "client_has_invoices"

    def __init__(self):
        super().__init__("Cannot delete a client that has invoices.")

PayloadTooLargeException

Raised by reject_large_body. Returns a 413 response with code payload_too_large.