在Java项目中,我们通常会将响应包装一层来实现统一响应格式,在Rocket中,我们也可以通过实现Responder
来返回统一的响应。
res.rs
rust
use crate::api::err::Error;
use rocket::response::Responder;
use rocket::serde::json::json;
use rocket::serde::{Deserialize, Serialize};
use rocket::Request;
#[derive(Serialize, Deserialize)]
pub struct Res<'a, T> {
code: i32,
msg: &'a str,
data: Option<T>,
}
impl<T> Res<T> {
pub fn success(data: T) -> Self {
Res {
code: 0,
msg: "",
data: Some(data),
}
}
pub fn error(msg: &str) -> Self {
Res {
code: 1,
msg,
data: None,
}
}
pub fn from_error(error: Error) -> Self {
Res {
code: error.0,
msg: error.1,
data: None,
}
}
}
impl<'r, 'o: 'r, T: Serialize> Responder<'r, 'o> for Res<T> {
fn respond_to(self, request: &'r Request<'_>) -> rocket::response::Result<'o> {
json!(&self).respond_to(request)
}
}
err.rs
rust
pub type Error<'a> = (i32, &'a str);
pub const ANY: Error = (1, "system error");
pub const SOURCE_NOT_EMPTY: Error = (1001, "source is not empty");
然后就可以按具体处理结果返回统一的失败或者成功响应:
-
成功:
rustRes::success(source)
-
失败:
rustRes::error("失败原因")
-
自定义失败code:
rustRes::from_error((10001,"失败原因"))
或者在err.rs中添加错误类型后:
rustRes::from_error(err::SOURCE_NOT_EMPTY)