1use core::fmt;
2use std::io;
3
4use crate::parse_error::ParseError;
5
6#[derive(Debug)]
7pub enum LssgErrorKind {
8 ParseError,
9 Render,
11 SiteTree,
13 Io,
14}
15
16#[derive(Debug)]
17pub struct LssgError {
18 message: String,
19 context: Option<String>,
20 kind: LssgErrorKind,
21}
22impl LssgError {
23 pub fn new<S: Into<String>>(message: S, kind: LssgErrorKind) -> LssgError {
24 LssgError {
25 message: message.into(),
26 kind,
27 context: None,
28 }
29 }
30
31 pub fn sitetree<S: Into<String>>(message: S) -> LssgError {
32 Self::new(message, LssgErrorKind::SiteTree)
33 }
34
35 pub fn render<S: Into<String>>(message: S) -> LssgError {
36 Self::new(message, LssgErrorKind::Render)
37 }
38
39 pub fn io<S: Into<String>>(message: S) -> LssgError {
40 Self::new(message, LssgErrorKind::Io)
41 }
42
43 pub fn with_context(mut self, context: impl Into<String>) -> Self {
44 self.context = Some(context.into());
45 self
46 }
47}
48impl From<ParseError> for LssgError {
49 fn from(error: ParseError) -> Self {
50 Self::new(&error.to_string(), LssgErrorKind::ParseError)
51 }
52}
53impl From<io::Error> for LssgError {
54 fn from(error: io::Error) -> Self {
55 Self::new(&error.to_string(), LssgErrorKind::Io)
56 }
57}
58
59impl std::error::Error for LssgError {}
60
61impl fmt::Display for LssgError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 let context = if let Some(context) = &self.context {
64 format!("with context '{context}'")
65 } else {
66 "".into()
67 };
68 write!(
69 f,
70 "Error when generating static files: '{}' {context}",
71 self.message
72 )
73 }
74}