Echo Writes Code

errors.rs

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
66
67
68
69
70
71
72
73
use axum::http::{ StatusCode };
use axum::response::{ IntoResponse, Response };

use std::io;
use std::fmt;
use std::num;

pub type Result<T> = ::std::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
	ConfigError(config::ConfigError),
	IoError(io::Error),
	TeraError(tera::Error),
	InvalidGitRoot(io::Error),
	InvalidPort(num::TryFromIntError),
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		use Error::*;

		match *self {
			ConfigError(ref e) => write!(f, "Config error: {}", e),
			IoError(ref e) => write!(f, "IO error: {}", e),
			TeraError(ref e) => write!(f, "Tera error: {}", e),
			InvalidGitRoot(ref e) => write!(f, "Invalid git.root: {}", e),
			InvalidPort(ref e) => write!(f, "Invalid network.port: {}", e),
		}
	}
}

impl From<config::ConfigError> for Error {
	fn from(e: config::ConfigError) -> Error {
		Error::ConfigError(e)
	}
}

impl From<io::Error> for Error {
	fn from(e: io::Error) -> Error {
		Error::IoError(e)
	}
}

impl From<tera::Error> for Error {
	fn from(e: tera::Error) -> Error {
		Error::TeraError(e)
	}
}

impl From<num::TryFromIntError> for Error {
	fn from(e: num::TryFromIntError) -> Error {
		Error::InvalidPort(e)
	}
}

impl IntoResponse for Error {
	fn into_response(self) -> Response {
		use Error::*;

		tracing::error!("Error when building response: {}", &self);

		let body = match self {
			ConfigError(..) => "The server encountered an unexpected error",
			IoError(..) => "The server encountered an unexpected error",
			TeraError(..) => "The server encountered an unexpected error",
			InvalidGitRoot(..) => "The server encountered an unexpected error",
			InvalidPort(..) => "The server encountered an unexpected error",
		};

		(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
	}
}