Help data structure for web framework response
Result
will become 500
using as web framework response type when Err(_)
, the action usually not I expect?
, the code will fill with if let
or match
that why I need a RespResult
, which can
RespResult::Err
, not always 500
Try
thus can using friendly ?
to simplify codenote: because the
Try
not stable yet, this crate needNightly
rust
add resp-result
into your crate
toml
[dependencies]
resp-result="*"
for-axum
: enable axum support, that will impl IntoResponse
for RespResult
(Default)
for-actix
eable actix-web support, that will impl Responder
for RespResult
extra-error
: enable extra error message in trait RespError
(Default)
log
: enable logging message on handling response (Default)axum-full
: equal to for-axum
+ extra-error
+ log
actix-full
: equal to for-actix
+ extra-error
+ log
RespResult<T,E>
require the E
impl the RespError
for example
```rust use resp_result::{RespError, RespResult}; use std::borrow::Cow; use http::StatusCode;
pub struct PlainError(String);
impl RespError for PlainError{ fn logmessage(&self) -> Cow<', str> { Cow::Owned(format!("PlainError: {}", self.0)) }
fn resp_message(&self) -> Cow<'_, str> {
"PlainError".into()
}
fn http_code(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
type ExtraMessage = String;
fn extra_message(&self) -> Self::ExtraMessage {
self.0.clone()
}
}
/// this can be use as handler return type
type PlainRResult
T
in RespResult<T, E>
The T
require implement Serialize
and has 'static
lifetime
the following is an example for using [RespResult
]
```rust use resp_result::{RespError, RespResult}; use std::borrow::Cow; use http::StatusCode;
pub struct PlainError(String);
impl RespError for PlainError{ fn logmessage(&self) -> Cow<', str> { Cow::Owned(format!("PlainError: {}", self.0)) }
type ExtraMessage = String;
fn extra_message(&self) -> Self::ExtraMessage {
self.0.clone()
}
}
/// this can be use as handler return type
type PlainRResult
pub async fn welcomeshortname(name: String) -> PlainRResult?
just like the function that return Result
Err(PlainError("the name size great then 8".to_string()))?;
}
if name.len() >= 4 {
// `Result::Ok` can convert into `RespResult::Success` just using `into`
Ok(format!("welcome! {name} with size great then 4")).into()
}else{
// or just direct using `RespResult::ok`
RespResult::ok(format!("welcome! {name}"))
}
} ```
In general the RespResult::Success
is always generate response with status code 200 OK
and using serde_json
serialize the body into json. But sometimes we want return an
304 Not Modified
with empty body to tell the client the resource do not change. To support above using situation, comes out the ExtraFlag
and ExtraFlags
extra flag have 4 different type can bring different effect on response
empty_body
: this flag will stop RespResult
perform serialize into response bodystatus
: this flag will overwrite StatusCode
of responseset-header
: this flag will insert or append provide header into response header mapremove-header
: this flag will remove header from response header mapdifferent extra flags can using +
to combine effect or +=
to adding effect
extra flags is a set of extra flag
flag wrap provide a wrap to send extra flag
when using extra flag, you need change return type from RespResult<T, E>
to RespResult<FlagWrap<T>, E>
the follow example change Status Code to 404 Not Found
```rust use resp_result::{RespError, RespResult, FlagWrap, ExtraFlag}; use std::borrow::Cow; use http::StatusCode;
pub struct PlainError(String);
impl RespError for PlainError{ fn logmessage(&self) -> Cow<', str> { Cow::Owned(format!("PlainError: {}", self.0)) }
type ExtraMessage = String;
fn extra_message(&self) -> Self::ExtraMessage {
self.0.clone()
}
}
/// this can be use as handler return type
type PlainRResult
pub async fn welcomeshortname(
name: String,
) -> PlainRResultwith_flags
to covert RespResultRespResult<FlagWrap<T>, E>
// using ()
for no extra flags
.withflags(())
}else{
// suing flag_ok
direct construct a flag with resp result
RespResult::flagok(
format!("Welcome! {name}"),
ExtraFlag::status(StatusCode::NOT_FOUND)
)
}
}
```
RespResult
behaviorby default the RespResult
will serialize the response body like that
json
{
"is-ok": true,
"error-message": "...",
"extra-msg": "...",
"body": null
}
the default behavior can be changed by using set_config
to set global configuration
for example, by config, we can change response body into following
json
{
"status": "fail",
"reterror": 10001,
"message": "something wrong",
"body": null
}