|
| 1 | +use std::borrow::BorrowMut; |
1 | 2 | use std::fmt::{self, Debug, Display};
|
2 | 3 |
|
3 | 4 | pub type Result<T> = std::result::Result<T, RoverError>;
|
4 | 5 |
|
| 6 | +use crate::Metadata; |
| 7 | + |
| 8 | +use ansi_term::Colour::{Cyan, Red}; |
| 9 | + |
5 | 10 | /// A specialized `Error` type for Rover.
|
6 | 11 | /// For now it's just a wrapper around `anyhow`, but
|
7 | 12 | /// eventually we'd like to add status codes and custom
|
8 | 13 | // Display implementations
|
9 | 14 | #[derive(Debug)]
|
10 | 15 | pub struct RoverError {
|
11 | 16 | error: anyhow::Error,
|
| 17 | + metadata: Metadata, |
12 | 18 | }
|
13 | 19 |
|
14 | 20 | impl RoverError {
|
15 | 21 | pub fn new<E>(error: E) -> Self
|
16 | 22 | where
|
17 | 23 | E: Into<anyhow::Error>,
|
18 | 24 | {
|
19 |
| - Self { |
20 |
| - error: error.into(), |
21 |
| - } |
| 25 | + let mut error = error.into(); |
| 26 | + let metadata = Metadata::from(error.borrow_mut()); |
| 27 | + |
| 28 | + Self { error, metadata } |
22 | 29 | }
|
23 | 30 | }
|
24 | 31 |
|
25 | 32 | impl Display for RoverError {
|
26 | 33 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
27 |
| - Display::fmt(&self.error, formatter) |
| 34 | + let error_descriptor_message = if let Some(code) = &self.metadata.code { |
| 35 | + format!("error[{}]:", code) |
| 36 | + } else { |
| 37 | + "error:".to_string() |
| 38 | + }; |
| 39 | + let error_descriptor = Red.bold().paint(&error_descriptor_message); |
| 40 | + writeln!(formatter, "{} {}", error_descriptor, &self.error)?; |
| 41 | + |
| 42 | + if let Some(solution) = &self.metadata.solution { |
| 43 | + let mut solution_descriptor_message = "".to_string(); |
| 44 | + for _ in 0..error_descriptor_message.len() + 1 { |
| 45 | + solution_descriptor_message.push(' '); |
| 46 | + } |
| 47 | + let solution_descriptor = Cyan.bold().paint(&solution_descriptor_message); |
| 48 | + write!(formatter, "{} {}", solution_descriptor, solution)?; |
| 49 | + } |
| 50 | + Ok(()) |
28 | 51 | }
|
29 | 52 | }
|
30 | 53 |
|
|
0 commit comments