Result type and the ? operator. Errors are automatically converted to appropriate HTTP responses, making error handling clean and consistent throughout your application.
The Response Type
Kit’s controller handlers returnResponse, which is an alias for Result<HttpResponse, HttpResponse>:
- Using the
?operator for automatic error conversion - Returning successful responses with
Ok(HttpResponse::...) - Returning error responses with
Err(HttpResponse::...)
Quick Error Handling with ?
The most common pattern is using the ? operator, which automatically converts errors to HTTP responses:
Error Types
AppError
AppError is a simple wrapper for creating inline/ad-hoc errors with custom status codes:
AppError Helper Methods
FrameworkError
FrameworkError is Kit’s comprehensive error enum that handles all framework-level errors:
FrameworkError Factory Methods
Automatic Error Conversion
Kit automatically converts common error types toFrameworkError:
Database Errors
SeaORM’sDbErr converts automatically:
Parameter Errors
Route parameter extraction returns errors usable with?:
AppError to FrameworkError
AppError converts to FrameworkError::Domain:
Error Response Format
Errors are automatically converted to JSON responses:Parameter Error (400)
Validation Error (422)
Generic Error
Creating Custom Domain Errors
Generating Errors with CLI
The fastest way to create a custom domain error is using the Kit CLI:- Create
src/errors/user_not_found.rswith a domain error struct - Create or update
src/errors/mod.rsto export the new error
The #[domain_error] Macro
The #[domain_error] macro automatically implements all necessary traits for HTTP error handling:
- Derives
DebugandClone - Implements
Display,Error, andHttpErrortraits - Implements
From<T> for FrameworkErrorfor seamless?usage
? operator:
Using AppError
For simple, inline errors:Implementing HttpError Trait
For reusable domain errors, implement theHttpError trait:
Creating Error Enums
For complex applications, create dedicated error enums:Common Error Patterns
Early Returns with ?
Validation Errors
Resource Not Found
Chaining Operations
Conditional Errors
Error Handling in Actions
Actions can returnResult<T, FrameworkError> for clean error propagation: