Skip to main content

spiral_server/
error.rs

1use std::{fmt::Display, sync::PoisonError};
2
3use actix_http::body::BoxBody;
4use actix_web::{HttpResponse, ResponseError};
5
6#[derive(Debug)]
7pub enum Error {
8    InvalidLength(usize, usize),
9    IoError(std::io::Error),
10    NotFound,
11    Unknown,
12}
13
14impl Display for Error {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        match self {
17            Error::IoError(io_error) => write!(f, "{}", io_error),
18            Error::NotFound => write!(f, "not found"),
19            Error::Unknown => write!(f, "unknown err"),
20            Error::InvalidLength(got, expected) => {
21                write!(f, "bad length: got {}, expected {}", got, expected)
22            }
23        }
24    }
25}
26
27impl std::error::Error for Error {}
28
29// TODO: add status_code() implementation to give better error info
30impl ResponseError for Error {
31    fn error_response(&self) -> HttpResponse<BoxBody> {
32        HttpResponse::with_body(self.status_code(), self.to_string()).map_into_boxed_body()
33    }
34}
35
36impl<T> From<PoisonError<T>> for Error {
37    fn from(_: PoisonError<T>) -> Self {
38        Error::Unknown
39    }
40}