RustWeb实战:构建优雅的ActixWeb统一错误处理在构建任何健壮的Web服务时,错误处理都是不可或缺的核心环节。一个优秀的服务不仅要在正常情况下稳定运行,更要在遇到数据库连接失败、用户输入非法、I/O异常等问题时,能给出清晰、统一且安全的响应。然而,将来自不同来源(如数据库
在构建任何健壮的 Web 服务时,错误处理都是不可或缺的核心环节。一个优秀的服务不仅要在正常情况下稳定运行,更要在遇到数据库连接失败、用户输入非法、I/O 异常等问题时,能给出清晰、统一且安全的响应。
然而,将来自不同来源(如数据库、序列化、业务逻辑)的错误整合成规范的 HTTP 响应,常常让代码变得混乱。本文将基于 Rust 及其高性能 Web 框架 Actix Web,通过一个完整的项目实例,手把手带你构建一个优雅、集中式的错误处理系统。你将学会如何利用 Rust 的类型系统和 Actix 的 ResponseError trait,将复杂的错误管理变得简单而高效。
enum Result<T, E> {
Ok(T),
Err(E),
}
use std::num::ParseIntError;
fn main() {
let result = square("25");
println!("{:?}", result);
}
fn square(val: &str) -> Result<i32, ParseIntError> {
match val.parse::<i32>() {
Ok(num) => Ok(num.pow(2)),
Err(e) => Err(3),
}
}
use std::num::ParseIntError;
fn main() {
let result = square("25");
println!("{:?}", result);
}
fn square(val: &str) -> Result<i32, ParseIntError> {
let num = val.parse::<i32>()?;
Ok(num ^ 2)
}
#[derive(Debug)]
pub enum MyError {
ParseError,
IOError,
}
actix_web::error::Error
std::error::Error
这个 traitws on main [✘!?] via 🦀 1.67.1 via 🅒 base
➜ tree -a -I target
.
├── .env
├── .git
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── README.md
└── webservice
├── Cargo.toml
└── src
├── bin
│ ├── server1.rs
│ └── teacher-service.rs
├── db_access.rs
├── errors.rs
├── handlers.rs
├── main.rs
├── models.rs
├── routers.rs
└── state.rs
40 directories, 47 files
ws on main [✘!?] via 🦀 1.67.1 via 🅒 base
use actix_web::{error, http::StatusCode, HttpResponse, Result};
use serde::Serialize;
use sqlx::error::Error as SQLxError;
use std::fmt;
#[derive(Debug, Serialize)]
pub enum MyError {
DBError(String),
ActixError(String),
NotFound(String),
}
#[derive(Debug, Serialize)]
pub struct MyErrorResponse {
error_message: String,
}
impl MyError {
fn error_response(&self) -> String {
match self {
MyError::DBError(msg) => {
println!("Database error occurred: {:?}", msg);
"Database error".into()
}
MyError::ActixError(msg) => {
println!("Server error occurred: {:?}", msg);
"Internal server error".into()
}
MyError::NotFound(msg) => {
println!("Not found error occurred: {:?}", msg);
msg.into()
}
}
}
}
impl error::ResponseError for MyError {
fn status_code(&self) -> StatusCode {
match self {
MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
MyError::NotFound(msg) => StatusCode::NOT_FOUND,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).json(MyErrorResponse {
error_message: self.error_response(),
})
}
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self)
}
}
impl From<actix_web::error::Error> for MyError {
fn from(err: actix_web::error::Error) -> Self {
MyError::ActixError(err.to_string())
}
}
impl From<SQLxError> for MyError {
fn from(err: SQLxError) -> Self {
MyError::DBError(err.to_string())
}
}
use actix_web::{web, App, HttpServer};
use dotenv::dotenv;
use sqlx::postgres::PgPoolOptions;
use std::env;
use std::io;
use std::sync::Mutex;
#[path = "../db_access.rs"]
mod db_access;
#[path = "../errors.rs"]
mod errors;
#[path = "../handlers.rs"]
mod handlers;
#[path = "../models.rs"]
mod models;
#[path = "../routers.rs"]
mod routers;
#[path = "../state.rs"]
mod state;
use routers::*;
use state::AppState;
#[actix_rt::main]
async fn main() -> io::Result<()> {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set.");
let db_pool = PgPoolOptions::new().connect(&database_url).await.unwrap();
let shared_data = web::Data::new(AppState {
health_check_response: "I'm Ok.".to_string(),
visit_count: Mutex::new(0),
// courses: Mutex::new(vec![]),
db: db_pool,
});
let app = move || {
App::new()
.app_data(shared_data.clone())
.configure(general_routes)
.configure(course_routes) // 路由注册
};
HttpServer::new(app).bind("127.0.0.1:3000")?.run().await
}
use super::errors::MyError;
use super::models::*;
use chrono::NaiveDateTime;
use sqlx::postgres::PgPool;
pub async fn get_courses_for_teacher_db(
pool: &PgPool,
teacher_id: i32,
) -> Result<Vec<Course>, MyError> {
let rows = sqlx::query!(
r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1"#,
teacher_id
)
.fetch_all(pool)
.await?;
let courses: Vec<Course> = rows
.iter()
.map(|row| Course {
id: Some(row.id),
teacher_id: row.teacher_id,
name: row.name.clone(),
time: Some(NaiveDateTime::from(row.time.unwrap())),
})
.collect();
match courses.len() {
0 => Err(MyError::NotFound("Courses not found teacher".into())),
_ => Ok(courses),
}
}
pub async fn get_courses_detail_db(pool: &PgPool, teacher_id: i32, course_id: i32) -> Course {
let row = sqlx::query!(
r#"SELECT id, teacher_id, name, time FROM course WHERE teacher_id = $1 and id = $2"#,
teacher_id,
course_id
)
.fetch_one(pool)
.await
.unwrap();
Course {
id: Some(row.id),
teacher_id: row.teacher_id,
name: row.name.clone(),
time: Some(NaiveDateTime::from(row.time.unwrap())),
}
}
pub async fn post_new_course_db(pool: &PgPool, new_course: Course) -> Course {
let row = sqlx::query!(
r#"INSERT INTO course (id, teacher_id, name) VALUES ($1, $2, $3)
RETURNING id, teacher_id, name, time"#,
new_course.id,
new_course.teacher_id,
new_course.name
)
.fetch_one(pool)
.await
.unwrap();
Course {
id: Some(row.id),
teacher_id: row.teacher_id,
name: row.name.clone(),
time: Some(NaiveDateTime::from(row.time.unwrap())),
}
}
use super::db_access::*;
use super::errors::MyError;
use super::state::AppState;
use actix_web::{web, HttpResponse};
pub async fn health_check_handler(app_state: web::Data<AppState>) -> HttpResponse {
let health_check_response = &app_state.health_check_response;
let mut visit_count = app_state.visit_count.lock().unwrap();
let response = format!("{} {} times", health_check_response, visit_count);
*visit_count += 1;
HttpResponse::Ok().json(&response)
}
use super::models::Course;
pub async fn new_course(
new_course: web::Json<Course>,
app_state: web::Data<AppState>,
) -> HttpResponse {
let course = post_new_course_db(&app_state.db, new_course.into()).await;
HttpResponse::Ok().json(course)
}
pub async fn get_courses_for_teacher(
app_state: web::Data<AppState>,
params: web::Path<usize>,
) -> Result<HttpResponse, MyError> {
let teacher_id = i32::try_from(params.into_inner()).unwrap();
get_courses_for_teacher_db(&app_state.db, teacher_id)
.await
.map(|courses| HttpResponse::Ok().json(courses))
}
pub async fn get_courses_detail(
app_state: web::Data<AppState>,
params: web::Path<(usize, usize)>,
) -> HttpResponse {
let teacher_id = i32::try_from(params.0).unwrap();
let course_id = i32::try_from(params.1).unwrap();
let course = get_courses_detail_db(&app_state.db, teacher_id, course_id).await;
HttpResponse::Ok().json(course)
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::http::StatusCode;
use dotenv::dotenv;
use sqlx::postgres::PgPoolOptions;
use std::env;
use std::sync::Mutex;
#[actix_rt::test] // 异步测试
async fn post_course_test() {
dotenv().ok();
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
let app_state: web::Data<AppState> = web::Data::new(AppState {
health_check_response: "".to_string(),
visit_count: Mutex::new(0),
db: db_pool,
});
let course = web::Json(Course {
teacher_id: 1,
name: "Test course".into(),
id: Some(3), // serial
time: None,
});
let resp = new_course(course, app_state).await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn get_all_courses_success() {
dotenv().ok();
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set");
let db_pool = PgPoolOptions::new().connect(&db_url).await.unwrap();
let app_state: web::Data<AppState> = web::Data::new(AppState {
health_check_response: "".to_string(),
visit_count: Mutex::new(0),
db: db_pool,
});
let teacher_id: web::Path<usize> = web::Path::from(1);
let resp = get_courses_for_tescher(app_state, teacher_id)
.await
.unwrap();
assert_eq!(...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!