Resp Result
Help data structure for web framework response
- waiting for try_trait_v2 stable
- Using Nightly Rust
Why
Result
will become500
using as web framework response type whenErr(_)
, the action usually not I expect- using non-Result type as web framework response type cannot using
?
, the code will fill withif let
ormatch
that why I need a RespResult
, which can
- control respond code or other message when it become
RespResult::Err
, not always500
- impl the
Try
thus can using friendly?
to simplify code
note: because the
Try
not stable yet, this crate needNightly
rust
Usage
Install
add resp-result
into your crate
[]
="*"
feature flags
-
for-axum
: enable axum support, that will implIntoResponse
forRespResult
(Default) -
for-actix
eable actix-web support, that will implResponder
forRespResult
-
extra-error
: enable extra error message in traitRespError
(Default) -
log
: enable logging message on handling response (Default) -
axum-full
: equal tofor-axum
+extra-error
+log
-
actix-full
: equal tofor-actix
+extra-error
+log
Define an Error
RespResult<T,E>
require the E
impl the RespError
for example
use ;
use Cow;
use StatusCode;
;
/// this can be use as handler return type
type PlainRResult<T> = ;
Bound of T
in RespResult<T, E>
The T
require implement Serialize
and has 'static
lifetime
Using it
the following is an example for using [RespResult
]
use ;
use Cow;
use StatusCode;
;
/// this can be use as handler return type
type PlainRResult<T> = ;
pub async
ExtraFlag and ExtraFlags
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
extra flag have 4 different type can bring different effect on response
empty_body
: this flag will stopRespResult
perform serialize into response bodystatus
: this flag will overwriteStatusCode
of responseset-header
: this flag will insert or append provide header into response header mapremove-header
: this flag will remove header from response header map
different extra flags can using +
to combine effect or +=
to adding effect
Extra Flags
extra flags is a set of extra flag
FlagWrap
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
use ;
use Cow;
use StatusCode;
;
/// this can be use as handler return type
type PlainRResult<T> = ;
pub async
Effect RespResult
behavior
by default the RespResult
will serialize the response body like that
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