Skip to main content

errors/
errors.rs

1/*
2Astrolog, a logging framework for Rust
3Copyright (C) 2019 Alessandro Pellizzari
4
5This library is free software; you can redistribute it and/or
6modify it under the terms of the GNU Lesser General Public
7License as published by the Free Software Foundation; either
8version 2.1 of the License, or (at your option) any later version.
9
10This library is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13Lesser General Public License for more details.
14
15You should have received a copy of the GNU Lesser General Public
16License along with this library; if not, write to the Free Software
17Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18*/
19
20extern crate astrolog;
21
22use std::env;
23use std::fs::File;
24use std::error::Error;
25use std::fmt;
26
27use astrolog::handler::console::ConsoleHandler;
28use astrolog::prelude::*;
29
30struct MyError {
31	msg: String,
32	cause: Option<Box<Error>>,
33}
34
35impl MyError {
36	pub fn new(msg: &str) -> MyError {
37		MyError {
38			msg: msg.into(),
39			cause: None,
40		}
41	}
42
43	pub fn with_cause<E: Error + 'static>(mut self, cause: E) -> Self {
44		self.cause = Some(Box::new(cause));
45		self
46	}
47}
48
49impl Error for MyError {
50	fn description(&self) -> &str {
51		&self.msg
52	}
53
54	fn cause(&self) -> Option<&Error> {
55		match &self.cause {
56			Some(c) => Some(c.as_ref()),
57			None => None,
58		}
59	}
60}
61
62impl fmt::Display for MyError {
63	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64		write!(f, "{}", self.description())
65	}
66}
67
68impl fmt::Debug for MyError {
69	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70		write!(f, "{}", self.description())
71	}
72}
73
74fn main() {
75	let logger = Logger::new()
76		.with_global("OS", env::consts::OS)
77		.with_handler(ConsoleHandler::new().with_levels_range(Level::Info, Level::Emergency));
78
79	let _ = File::open("foo.txt")
80		.map_err(|e| {
81			logger.with_error(&e).error("Simple error opening foo.txt")
82		});
83
84	let _ = File::open("foo.txt")
85		.map_err(|e| {
86			let e_with_trace = MyError::new("Opening foo.txt").with_cause(e);
87			logger.with_error(&e_with_trace).error("Tracing error opening file")
88		});
89
90	let _ = File::open("foo.txt")
91		.map_err(|e| {
92			let e_with_trace = MyError::new("Opening foo.txt").with_cause(MyError::new("second-level error").with_cause(e));
93			logger.with_error(&e_with_trace).error("Deep tracing error opening file")
94		});
95}