diff options
author | Martin Fischer <martin@push-f.com> | 2021-01-17 19:06:58 +0100 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2021-01-17 20:02:05 +0100 |
commit | 61efc35b0a9c62c18a7a98419bf2ddbc0a52a42d (patch) | |
tree | ff0ef6604da7b19c0bee5785e93df4844fcc9c17 /src/error.rs |
publishv0.1.0
Diffstat (limited to 'src/error.rs')
-rw-r--r-- | src/error.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..d40ddf3 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,44 @@ +use std::fmt::Display; + +use hyper::StatusCode; + +/// Encapsulates a status code and an error message. +#[derive(Debug)] +pub struct Error { + pub code: StatusCode, + pub message: String, +} + +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "error: {}", self.message) + } +} + +impl std::error::Error for Error { +} + +impl Error { + /// Returns an HTTP response builder with the status code set to `self.code`. + pub fn response_builder(&self) -> hyper::http::response::Builder { + hyper::Response::builder().status(self.code) + } + + // some conventient constructors for common errors + + pub fn bad_request(message: String) -> Self { + Error{code: StatusCode::BAD_REQUEST, message} + } + pub fn not_found(message: String) -> Self { + Error{code: StatusCode::NOT_FOUND, message} + } + pub fn unauthorized(message: String) -> Self { + Error{code: StatusCode::UNAUTHORIZED, message} + } + pub fn internal(message: String) -> Self { + Error{code: StatusCode::INTERNAL_SERVER_ERROR, message} + } + pub fn method_not_allowed(message: String) -> Self { + Error{code: StatusCode::METHOD_NOT_ALLOWED, message} + } +}
\ No newline at end of file |