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
use std::{error::Error as StdError, fmt::Debug};

use crate::Context;

#[derive(Debug)]
pub struct Error<TContext>
where
	TContext: Context + Debug + Send + Sync,
{
	pub(crate) context: Option<TContext>,
	pub(crate) message: String,
	pub(crate) status: u16,
	pub(crate) error: Box<dyn StdError + Send>,
}

impl<TContext> Error<TContext>
where
	TContext: Context + Debug + Send + Sync,
{
	pub fn new(
		context: Option<TContext>,
		message: String,
		status: u16,
		error: Box<dyn StdError + Send>,
	) -> Self {
		Error {
			context,
			message,
			status,
			error,
		}
	}

	pub fn get_context(&mut self) -> Option<&mut TContext> {
		self.context.as_mut()
	}
}

impl<TContext, StdErr> From<StdErr> for Error<TContext>
where
	TContext: Context + Debug + Send + Sync,
	StdErr: 'static + StdError + Send,
{
	fn from(err: StdErr) -> Self {
		Error {
			context: None,
			message: String::from("Internal Server Error"),
			status: 500,
			error: Box::new(err),
		}
	}
}