summaryrefslogtreecommitdiff
path: root/src/errors.rs
blob: 51ac8fdb9b20dbedb71f818ee29ae89bdf2f6ffe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use rocket::http::ContentType;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rspotify::client::ClientError;
use rspotify::client::Spotify;
use std::collections::HashMap;
use std::io::Cursor;
use std::sync::{MutexGuard, PoisonError};
use tokio_postgres::Error as DbError;

#[derive(Debug)]
pub enum Error {
    Postgres(DbError),
    Spotify(ClientError),
    Misc(String),
}
impl From<DbError> for Error {
    fn from(error: DbError) -> Self {
        Error::Postgres(error)
    }
}
impl From<ClientError> for Error {
    fn from(error: ClientError) -> Self {
        Error::Spotify(error)
    }
}
impl From<&str> for Error {
    fn from(error: &str) -> Self {
        Error::Misc(error.to_owned())
    }
}
impl From<String> for Error {
    fn from(error: String) -> Self {
        Error::Misc(error)
    }
}
impl<'a> From<PoisonError<MutexGuard<'a, HashMap<String, (String, Spotify)>>>> for Error {
    fn from(error: PoisonError<MutexGuard<'a, HashMap<String, (String, Spotify)>>>) -> Self {
        Error::Misc(format!("failed to lock the client mutex: {:?}", error))
    }
}
impl<'a> From<PoisonError<MutexGuard<'a, tokio_postgres::Client>>> for Error {
    fn from(error: PoisonError<MutexGuard<'a, tokio_postgres::Client>>) -> Self {
        Error::Misc(format!("failed to lock the client mutex: {:?}", error))
    }
}
impl<'a> From<std::option::NoneError> for Error {
    fn from(error: std::option::NoneError) -> Self {
        Error::Misc(format!("tried to unwrap none at: {:?}", error))
    }
}
impl<'a> Responder<'a, 'a> for Error {
    fn respond_to(self, _: &Request) -> response::Result<'a> {
        let response = match self {
            Error::Postgres(e) => format!("DB Error: {:?}", e),
            Error::Spotify(e) => format!("Spotify Error: {:?}", e),
            Error::Misc(e) => format!("Error: {}", e),
        };
        Response::build()
            .header(ContentType::Plain)
            .status(rocket::http::Status::raw(500))
            .sized_body(response.len(), Cursor::new(response))
            .ok()
    }
}