aboutsummaryrefslogtreecommitdiff
path: root/src/model/helper/error.rs
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2022-01-03 13:58:05 +0100
committerAlex Auvolat <alex@adnab.me>2022-01-04 12:52:46 +0100
commitbeeef4758e5ec0d521179a799a3237c2c0368911 (patch)
treeeb2734647b3c6e62cef64a5f2b533ac694252c29 /src/model/helper/error.rs
parentd8ab5bdc3e20759e5ba8a6844393757da3539372 (diff)
downloadgarage-beeef4758e5ec0d521179a799a3237c2c0368911.tar.gz
garage-beeef4758e5ec0d521179a799a3237c2c0368911.zip
Some movement of helper code and refactoring of error handling
Diffstat (limited to 'src/model/helper/error.rs')
-rw-r--r--src/model/helper/error.rs51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/model/helper/error.rs b/src/model/helper/error.rs
new file mode 100644
index 00000000..b9b515f3
--- /dev/null
+++ b/src/model/helper/error.rs
@@ -0,0 +1,51 @@
+use err_derive::Error;
+use serde::{Deserialize, Serialize};
+
+use garage_util::error::Error as GarageError;
+
+#[derive(Debug, Error, Serialize, Deserialize)]
+pub enum Error {
+ #[error(display = "Internal error: {}", _0)]
+ Internal(#[error(source)] GarageError),
+
+ #[error(display = "Bad request: {}", _0)]
+ BadRequest(String),
+}
+
+impl From<netapp::error::Error> for Error {
+ fn from(e: netapp::error::Error) -> Self {
+ Error::Internal(GarageError::Netapp(e))
+ }
+}
+
+pub trait OkOrBadRequest {
+ type S;
+ fn ok_or_bad_request<M: AsRef<str>>(self, reason: M) -> Result<Self::S, Error>;
+}
+
+impl<T, E> OkOrBadRequest for Result<T, E>
+where
+ E: std::fmt::Display,
+{
+ type S = T;
+ fn ok_or_bad_request<M: AsRef<str>>(self, reason: M) -> Result<T, Error> {
+ match self {
+ Ok(x) => Ok(x),
+ Err(e) => Err(Error::BadRequest(format!(
+ "{}: {}",
+ reason.as_ref(),
+ e.to_string()
+ ))),
+ }
+ }
+}
+
+impl<T> OkOrBadRequest for Option<T> {
+ type S = T;
+ fn ok_or_bad_request<M: AsRef<str>>(self, reason: M) -> Result<T, Error> {
+ match self {
+ Some(x) => Ok(x),
+ None => Err(Error::BadRequest(reason.as_ref().to_string())),
+ }
+ }
+}