Explicit error http
Built on top of explicit-error
, it provides idiomatic tools to manage errors that generate an HTTP response.
Based on the explicit-error crate, its chore tenet is to favor explicitness by inlining the error output while remaining concise.
The key features are:
- Explicitly mark any error wrapped in a [Result] as a [Fault]. A backtrace is captured and a 500 Internal Server HTTP response generated.
- A derive macro HttpError to easily declare how enum or struct errors transform into an [Error], i.e. defines the generated HTTP response.
- Inline transformation of any errors wrapped in a [Result] into an [Error].
- Add context to errors to help debug.
- Monitor errors before they are transformed into proper HTTP responses. The implementation is different depending on the web framework used, to have more details refer to the
Web frameworks
section.
A tour of explicit-error-http
The cornerstone of the library is the [Error] type. Use Result<T, explicit_error_http::Error>
, or equivalently explicit_error_http::Result<T>
, as the return type of any faillible function returning errors that convert to an HTTP response.
Usually, it is mostly functions either called by handlers or middlewares.
Inline
In the body of the function you can explicitly turn errors into HTTP response using [HttpError] or marking them as [Fault].
use StatusCode;
use ProblemDetails;
use Uri;
use ;
// Import the prelude to enable functions on std::result::Result
Note: The crate [problem_details] is used as an example for the HTTP response body. You can, of course, use whatever you would like that implements Serialize.
Enum and struct
Domain errors are often represented as enum or struct as they are raised in different places.
To easily enable the conversion to [Error] use the HttpError derive and implement From<&MyError> for HttpError
.
use StatusCode;
use ProblemDetails;
use Uri;
use ;
Note: The HttpError derive implements the conversion to [Error], the impl of Display (json format) and [std::error::Error].
Pattern matching
One of the drawbacks of using one and only one return type for different domain functions is that callers loose the ability to pattern match on the returned error.
A solution is provided using try_map_on_source on any Result<T, Error>
, or equivalently explicit_error_http::Result<T>
.
Note: under the hood try_map_on_source perform some downcasting.
Web frameworks
explicit-error-http integrates well with most popular web frameworks by providing a feature flag for each of them.
Actix web
The type [Error] cannot directly be used as handlers or middlewares returned [Err] variant. A dedicated type is required. The easiest implementation is to declare a Newtype, derive it with the [HandlerError] and implement the [HandlerError] trait.
;
async