[actix-web]感觉这么写好丑呀,求推荐新写法

52 天前
 RedBeanIce
```rust
use actix_http::header::TryIntoHeaderPair;
use actix_http::StatusCode;
use actix_web::http::header::ContentType;
use actix_web::HttpResponse;
use serde::{Deserialize, Serialize};

// 自定义 Response
#[derive(Deserialize, Serialize, Debug)]
pub(crate) struct R<T> {
pub(crate) code: i32,
pub(crate) msg: String,
pub(crate) data: Option<T>,
}

// 在 R<T> 结构体附近定义辅助方法
impl<T> R<T>
where
T: Serialize,
{
// 创建成功的响应
pub fn success(data: T) -> HttpResponse {
let r: R<T> = R {
code: StatusCode::OK.as_u16() as i32,
msg: "请求成功".to_string(),
data: Some(data),
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}

// 创建失败的响应
pub fn err() -> HttpResponse {
let r: R<()> = R {
code: StatusCode::INTERNAL_SERVER_ERROR.as_u16() as i32,
msg: "服务器异常".to_string(),
data: None,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}

// 创建失败的响应
pub fn err_msg(msg: String) -> HttpResponse {
let r: R<()> = R {
code: StatusCode::INTERNAL_SERVER_ERROR.as_u16() as i32,
msg,
data: None,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}

// 创建自定义状态码的响应
pub fn custom(code: i32, msg: String, data: Option<T>) -> HttpResponse {
let r: R<T> = R {
code,
msg,
data,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}
}
```

```rust
#[post("/api/v1/deposits/list")]
async fn deposits_list(pool: web::Data<PgPool>) -> impl Responder {
let list = Deposit::list(&pool).await;
match list {
Ok(list) => R::success(list),
Err(e) => {
// 处理错误,例如返回一个错误响应
eprintln!("Error querying deposits: {:?}", e);
// 假设 R::error 是你用来处理错误响应的方法
return R::<String>::err_msg("Failed to fetch deposits".to_string());
}
}
}

```
1512 次点击
所在节点    Rust
2 条回复
lsk569937453
52 天前
好吧,一直用 axum 的路过。。。
dyc12389
52 天前
定义一个 Error 的枚举,derive(this_error::Error)

impl actix_web::ResponseError for Error {
}

所有路由的 handler 返回都可以用 actix_web::Result
这样就把这个框架里的 error 统一起来了

正常的返回就用你封装的 response 就行

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1060186

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX