Actix Web: Middleware, Scopes & Errors
Middleware
App::new()
.wrap(Logger::default())
.wrap(Cors::permissive())
.service(get_user)
// .wrap() chains middleware into the request-processing
// pipeline for all routes registered on that App/scopeOrganizing Routes With Scopes
App::new().service(
web::scope("/api/v1")
.wrap(AuthMiddleware)
.service(get_user)
.service(create_user)
)
// Shared prefix + shared middleware for a related group of routesCustom Error Handling
impl ResponseError for AppError {
fn error_response(&self) -> HttpResponse {
match self {
AppError::NotFound => HttpResponse::NotFound().finish(),
AppError::Validation(msg) => HttpResponse::BadRequest().body(msg.clone()),
}
}
}
// Maps different failure conditions to appropriate HTTP
// responses, instead of collapsing everything into a 500Testing
Actix Web's test module (test::TestRequest) builds mock requests and invokes handlers/services directly in async test functions, without needing a fully running server.
Why Rust/Actix Web for Performance-Critical Services
No garbage collector means no unpredictable GC pause times -- valuable for services where consistent, predictable low latency and raw throughput are priorities, at the cost of Rust's steeper learning curve versus a more permissive, dynamically-typed framework.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free