bit better error handling

This commit is contained in:
2021-05-19 20:13:00 +02:00
parent 204fe4d942
commit e5b77edeae
5 changed files with 75 additions and 22 deletions

View File

@ -1,34 +1,50 @@
pub enum ErrorKind {
InvalidEndpoint,
InvalidEndpointError,
JsonParseError,
DatabaseError,
}
pub struct Error {
kind: ErrorKind,
desc: Option<String>,
}
impl Error {
pub fn new(kind: ErrorKind) -> Error {
Error {
kind,
}
}
}
impl From<serde_json::Error> for Error {
fn from(_: serde_json::Error) -> Self {
Error {
kind: ErrorKind::JsonParseError,
}
Error { kind, desc: None }
}
}
impl ToString for Error {
fn to_string(&self) -> String {
match self.kind {
ErrorKind::InvalidEndpoint => "invalid endpoint",
ErrorKind::JsonParseError => "JSON parse error",
}.to_string()
let mut error = match self.kind {
ErrorKind::InvalidEndpointError => "invalid endpoint",
ErrorKind::JsonParseError => "unable to parse JSON data",
ErrorKind::DatabaseError => "unable to connect to database",
}
.to_string();
if let Some(desc) = &self.desc {
error += ": ";
error += desc;
}
error
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Error {
kind: ErrorKind::JsonParseError,
desc: Some(error.to_string()),
}
}
}
impl From<r2d2::Error> for Error {
fn from(error: r2d2::Error) -> Self {
Error {
kind: ErrorKind::DatabaseError,
desc: Some(error.to_string()),
}
}
}