1use clap::Error as ClapError;
2use indicatif::style::TemplateError;
3use owo_colors::{OwoColorize, Stream::Stderr, Style};
4use reqwest::Error as ReqError;
5use serde_json::Error as SerdeJSONError;
6use std::io::Error as IOError;
7use std::{error::Error as StdError, fmt, result};
8
9pub type Result<T> = result::Result<T, Error>;
10
11#[derive(Debug)]
12pub struct Error(Box<ErrorKind>);
13
14impl Error {
15 pub(crate) fn new(kind: ErrorKind) -> Error {
17 Error(Box::new(kind))
18 }
19
20 pub fn kind(&self) -> &ErrorKind {
22 &self.0
23 }
24
25 pub fn is_broken_pipe(&self) -> bool {
28 matches!(&*self.0, ErrorKind::IO(e) if e.kind() == std::io::ErrorKind::BrokenPipe)
29 }
30
31 pub fn into_kind(self) -> ErrorKind {
33 *self.0
34 }
35}
36
37#[derive(Debug)]
38pub enum ErrorKind {
39 GenericCli(String),
41 Cli(ClapError),
43 IO(IOError),
45 FormatTSV(String),
47 Reqwest(ReqError),
49 SerdeJSON(SerdeJSONError),
51 Expression(String),
53 Variable(String),
55 TaxRank(String),
57 Progress(TemplateError),
59 Report(String),
61 Api(String),
63}
64
65impl From<ClapError> for Error {
66 fn from(err: ClapError) -> Self {
67 Error::new(ErrorKind::Cli(err))
68 }
69}
70
71impl From<IOError> for Error {
72 fn from(err: IOError) -> Self {
73 Error::new(ErrorKind::IO(err))
74 }
75}
76
77impl From<ReqError> for Error {
78 fn from(err: ReqError) -> Self {
79 Error::new(ErrorKind::Reqwest(err))
80 }
81}
82
83impl From<SerdeJSONError> for Error {
84 fn from(err: SerdeJSONError) -> Self {
85 Error::new(ErrorKind::SerdeJSON(err))
86 }
87}
88
89impl From<TemplateError> for Error {
90 fn from(err: TemplateError) -> Self {
91 Error::new(ErrorKind::Progress(err))
92 }
93}
94
95impl StdError for Error {}
96
97impl fmt::Display for Error {
98 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 write!(
100 f,
101 "{} in goat-cli:\n\t",
102 "error".if_supports_color(Stderr, |text| {
103 let style = Style::new().red().bold();
104 text.style(style)
105 })
106 )?;
107
108 match &*self.0 {
109 ErrorKind::Cli(err) => write!(f, "command line error (clap) - {}", err),
110 ErrorKind::GenericCli(err) => write!(f, "command line error - {}", err),
111 ErrorKind::IO(err) => write!(f, "I/O error - {}", err),
112 ErrorKind::FormatTSV(err) => write!(f, "format TSV error - {}", err),
113 ErrorKind::Reqwest(err) => write!(f, "request error - {}", err),
114 ErrorKind::Expression(err) => write!(f, "expression error - {}", err),
115 ErrorKind::Variable(err) => write!(f, "variable error - {}", err),
116 ErrorKind::TaxRank(err) => write!(f, "tax rank error - {}", err),
117 ErrorKind::SerdeJSON(err) => write!(f, "serialising JSON error - {}", err),
118 ErrorKind::Progress(err) => write!(f, "progress bar error - {}", err),
119 ErrorKind::Report(err) => write!(f, "report error - {}", err),
120 ErrorKind::Api(err) => write!(f, "GoaT API error - {}", err),
121 }
122 }
123}