1use std::convert::TryFrom;
2
3use hyper::{http, Body, Response, StatusCode};
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum ServerError {
8 #[error("unauthorized access")]
9 Unauthorized,
10
11 #[error("object not found")]
12 NotFound,
13
14 #[error("invalid query")]
15 InvalidQuery,
16
17 #[error("endpoint gone")]
18 Gone,
19
20 #[error("internal database error")]
21 Database(#[from] rusqlite::Error),
22
23 #[error("internal WireGuard error")]
24 WireGuard,
25
26 #[error("internal I/O error")]
27 Io(#[from] std::io::Error),
28
29 #[error("JSON parsing/serialization error")]
30 Json(#[from] serde_json::Error),
31
32 #[error("Generic HTTP error")]
33 Http(#[from] http::Error),
34
35 #[error("Generic Hyper error")]
36 Hyper(#[from] hyper::Error),
37}
38
39impl From<&ServerError> for StatusCode {
40 fn from(error: &ServerError) -> StatusCode {
41 use ServerError::*;
42 match error {
43 Unauthorized => StatusCode::UNAUTHORIZED,
44 NotFound => StatusCode::NOT_FOUND,
45 Gone => StatusCode::GONE,
46 InvalidQuery | Json(_) => StatusCode::BAD_REQUEST,
47 Database(rusqlite::Error::SqliteFailure(libsqlite3_sys::Error { code, .. }, ..))
49 if *code == libsqlite3_sys::ErrorCode::ConstraintViolation =>
50 {
51 StatusCode::BAD_REQUEST
52 },
53 Database(rusqlite::Error::QueryReturnedNoRows) => StatusCode::NOT_FOUND,
54 WireGuard | Io(_) | Database(_) | Http(_) | Hyper(_) => {
55 StatusCode::INTERNAL_SERVER_ERROR
56 },
57 }
58 }
59}
60
61impl TryFrom<ServerError> for Response<Body> {
62 type Error = http::Error;
63
64 fn try_from(e: ServerError) -> Result<Self, Self::Error> {
65 Response::builder()
66 .status(StatusCode::from(&e))
67 .body(Body::empty())
68 }
69}