Rust Web 全堆疊開發之 Web Service 中的錯誤處理
Web Service 中的統一錯誤處理
Actix Web Service 自定義錯誤型別 -> 自定義錯誤轉為 HTTP Response
- 資料庫
- 資料庫錯誤
- 串行化
- serde 錯誤
- I/O 操作
- I/O 錯誤
- Actix-Web 庫
- Actix 錯誤
- 用戶非法輸入
- 用戶非法輸入錯誤
Actix-Web 的錯誤處理
- 編程語言常用的兩種錯誤處理方式:
- 例外
- 回傳值( Rust 使用這種)
- Rust 希望開發者顯式的處理錯誤,因此,可能出錯的函式回傳Result 列舉型別,其定義如下:
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),
}
}
? 運算子
- 在某函式中使用 ? 運算子,該運算子嘗試從 Result 中獲取值:
- 如果不成功,它就會接收 Error ,中止函式執行,并把錯誤傳播到呼叫該函式的函式,
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 把錯誤轉化為 HTTP Response
- Actix-Web 定義了一個通用的錯誤型別( struct ):
actix_web::error::Error- 它實作了
std::error::Error這個 trait
- 它實作了
- 任何實作了標準庫 Error trait 的型別,都可以通過 ? 運算子,轉化為 Actix 的 Error 型別
- Actix 的 Error 型別會自動的轉化為 HTTP Response ,回傳給客戶端,
- ResponseError trait :任何實作該 trait 的錯誤均可轉化為HTTP Response 訊息,
- 內置的實作: Actix-Web 對于常見錯誤有內置的實作,例如:
- Rust 標準 I/O 錯誤
- Serde 錯誤
- Web 錯誤,例如: ProtocolError 、 Utf8Error 、 ParseError 等等
- 其它錯誤型別:內置實作不可用時,需要自定義實作錯誤到 HTTP Response 的轉換
創建自定義錯誤處理器
- 創建一個自定義錯誤型別
- 實作 From trait ,用于把其它錯誤型別轉化為該型別
- 為自定義錯誤型別實作 ResponseError trait
- 在 handler 里回傳自定義錯誤型別
- Actix 會把錯誤轉化為 HTTP 回應
專案目錄
ws 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
webservice/src/errors.rs
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())
}
}
webservice/src/bin/teacher-service.rs
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
}
webservice/src/db_access.rs
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())),
}
}
webservice/src/handlers.rs
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_tescher(
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!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn get_one_course_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 params: web::Path<(usize, usize)> = web::Path::from((1, 1));
let resp = get_courses_detail(app_state, params).await;
assert_eq!(resp.status(), StatusCode::OK);
}
}
測驗
ws on main via ?? 1.67.1 via ?? base
? cargo test --bin teacher-service get_all_courses_success
Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:39:30
|
39 | MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ^^^ ^^^
|
= note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
|
39 | MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ~~~~ ~~~~
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:40:31
|
40 | MyError::NotFound(msg) => StatusCode::NOT_FOUND,
| ^^^ help: if this is intentional, prefix it with an underscore: `_msg`
warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
Finished test [unoptimized + debuginfo] target(s) in 1.55s
Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)
running 1 test
test handlers::tests::get_all_courses_success ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.01s
ws on main [?!?] via ?? 1.67.1 via ?? base took 2.1s
?
webservice/src/db_access.rs
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,
) -> Result<Course, MyError> {
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;
if let Ok(row) = row {
Ok(Course {
id: Some(row.id),
teacher_id: row.teacher_id,
name: row.name.clone(),
time: Some(NaiveDateTime::from(row.time.unwrap())),
})
} else {
Err(MyError::NotFound("Course Id not found".into()))
}
}
pub async fn post_new_course_db(pool: &PgPool, new_course: Course) -> Result<Course, MyError> {
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?;
Ok(Course {
id: Some(row.id),
teacher_id: row.teacher_id,
name: row.name.clone(),
time: Some(NaiveDateTime::from(row.time.unwrap())),
})
}
webservice/src/handlers.rs
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>,
) -> Result<HttpResponse, MyError> {
post_new_course_db(&app_state.db, new_course.into())
.await
.map(|course| HttpResponse::Ok().json(course))
}
pub async fn get_courses_for_tescher(
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)>,
) -> Result<HttpResponse, MyError> {
let teacher_id = i32::try_from(params.0).unwrap();
let course_id = i32::try_from(params.1).unwrap();
get_courses_detail_db(&app_state.db, teacher_id, course_id)
.await
.map(|course| 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;
#[ignore]
#[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(5), // serial
time: None,
});
let resp = new_course(course, app_state).await.unwrap();
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!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn get_one_course_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 params: web::Path<(usize, usize)> = web::Path::from((1, 1));
let resp = get_courses_detail(app_state, params).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
}
測驗
ws on main [?!?] via ?? 1.67.1 via ?? base took 2.1s
? cargo test --bin teacher-service
Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:39:30
|
39 | MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ^^^ ^^^
|
= note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
|
39 | MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ~~~~ ~~~~
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:40:31
|
40 | MyError::NotFound(msg) => StatusCode::NOT_FOUND,
| ^^^ help: if this is intentional, prefix it with an underscore: `_msg`
warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
Finished test [unoptimized + debuginfo] target(s) in 1.27s
Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)
running 3 tests
test handlers::tests::get_one_course_success ... ok
test handlers::tests::get_all_courses_success ... ok
test handlers::tests::post_course_test ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
ws on main [?!?] via ?? 1.67.1 via ?? base
?
ws on main [?!?] via ?? 1.67.1 via ?? base
? cargo test --bin teacher-service
Compiling webservice v0.1.0 (/Users/qiaopengjun/rust/ws/webservice)
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:39:30
|
39 | MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ^^^ ^^^
|
= note: `#[warn(unused_variables)]` on by default
help: if this is intentional, prefix it with an underscore
|
39 | MyError::DBError(_msg) | MyError::ActixError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
| ~~~~ ~~~~
warning: unused variable: `msg`
--> webservice/src/bin/../errors.rs:40:31
|
40 | MyError::NotFound(msg) => StatusCode::NOT_FOUND,
| ^^^ help: if this is intentional, prefix it with an underscore: `_msg`
warning: `webservice` (bin "teacher-service" test) generated 2 warnings (run `cargo fix --bin "teacher-service" --tests` to apply 2 suggestions)
Finished test [unoptimized + debuginfo] target(s) in 0.71s
Running unittests src/bin/teacher-service.rs (target/debug/deps/teacher_service-32d6a48d6ee3c4b4)
running 3 tests
test handlers::tests::post_course_test ... ignored
test handlers::tests::get_one_course_success ... ok
test handlers::tests::get_all_courses_success ... ok
test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.01s
ws on main [?!?] via ?? 1.67.1 via ?? base
?
本文來自博客園,作者:QIAOPENGJUN,轉載請注明原文鏈接:https://www.cnblogs.com/QiaoPengjun/p/17445127.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553920.html
標籤:其他
上一篇:驅動開發:內核決議PE結構匯出表
下一篇:返回列表
