litekv/
api.rs

1////!
2////! LiteKV -- A tiny key-value store with a simple REST API backed by SQLite.
3////! Copyright (c) 2021 SilentByte <https://silentbyte.com/>
4////!
5
6use actix_web::http::StatusCode;
7use actix_web::ResponseError;
8
9impl std::fmt::Debug for ApiError {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        error_chain_fmt(self, f)
12    }
13}
14
15fn error_chain_fmt(
16    e: &impl std::error::Error,
17    f: &mut std::fmt::Formatter<'_>,
18) -> std::fmt::Result {
19    writeln!(f, "{}\n", e)?;
20    let mut current = e.source();
21    while let Some(cause) = current {
22        writeln!(f, "Caused by:\n\t{}", cause)?;
23        current = cause.source();
24    }
25    Ok(())
26}
27
28#[derive(thiserror::Error)]
29pub enum ApiError {
30    #[error(transparent)]
31    UnknownError(#[from] anyhow::Error),
32
33    #[error("Value with key '{0}' could not be found")]
34    ValueNotFound(String),
35
36    #[error("Data Store is in read-only mode")]
37    ReadonlyDataStore,
38}
39
40impl ResponseError for ApiError {
41    fn status_code(&self) -> StatusCode {
42        match self {
43            ApiError::UnknownError(_) => StatusCode::INTERNAL_SERVER_ERROR,
44            ApiError::ValueNotFound(_) => StatusCode::NOT_FOUND,
45            ApiError::ReadonlyDataStore => StatusCode::FORBIDDEN,
46        }
47    }
48}