1use std::{
17 backtrace::{Backtrace, BacktraceStatus},
18 fmt, process,
19};
20
21use anyhow::{Error, Result};
22use log::{Level, log_enabled};
23use schemars::JsonSchema;
24use serde::{Serialize, Serializer};
25
26use crate::printer::Printer;
27
28pub trait ErrorCode: Clone + fmt::Debug + Serialize + JsonSchema + Send + Sync + 'static {}
35
36impl<T: Clone + fmt::Debug + Serialize + JsonSchema + Send + Sync + 'static> ErrorCode for T {}
37
38#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
40pub enum NoErrorCode {}
41
42#[derive(Debug)]
44pub struct CodedError<C> {
45 code: C,
46 message: String,
47}
48
49impl<C> CodedError<C> {
50 pub fn new(code: C, message: impl Into<String>) -> Self {
52 Self {
53 code,
54 message: message.into(),
55 }
56 }
57}
58
59impl<C> fmt::Display for CodedError<C> {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.write_str(&self.message)
62 }
63}
64
65impl<C: fmt::Debug> std::error::Error for CodedError<C> {}
66
67pub const EXIT_FAILURE: i32 = 1;
70
71pub const EXIT_PARTIAL: i32 = 2;
75
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub struct PartialOutcome {
85 status: i32,
86}
87
88impl PartialOutcome {
89 pub fn new(status: i32) -> Self {
96 assert!(
97 status >= EXIT_PARTIAL,
98 "partial outcome status {status} < 2"
99 );
100 Self { status }
101 }
102
103 pub fn status(&self) -> i32 {
105 self.status
106 }
107}
108
109impl Default for PartialOutcome {
110 fn default() -> Self {
111 Self::new(EXIT_PARTIAL)
112 }
113}
114
115impl fmt::Display for PartialOutcome {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 write!(f, "Command ended with exit status {}", self.status)
118 }
119}
120
121impl std::error::Error for PartialOutcome {}
122
123pub fn partial_outcome_of(err: &Error) -> Option<PartialOutcome> {
125 err.chain()
126 .find_map(|cause| cause.downcast_ref::<PartialOutcome>())
127 .copied()
128}
129
130pub fn code_of<C: ErrorCode>(err: &Error) -> Option<C> {
132 err.chain()
133 .find_map(|cause| cause.downcast_ref::<CodedError<C>>())
134 .map(|coded| coded.code.clone())
135}
136
137pub struct ErrorReport<C = NoErrorCode> {
140 error: Error,
141 code: Option<C>,
142 pub(crate) log_level_hint: &'static str,
144}
145
146impl ErrorReport {
147 pub fn eval<T>(printer: &mut impl Printer, result: Result<T, Error>) -> T {
150 Self::eval_coded(printer, result)
151 }
152}
153
154impl<C: ErrorCode> ErrorReport<C> {
155 pub fn eval_coded<T>(printer: &mut impl Printer, result: Result<T, Error>) -> T {
161 match result {
162 Ok(res) => res,
163 Err(err) => {
164 if let Some(outcome) = partial_outcome_of(&err) {
165 process::exit(outcome.status());
166 }
167
168 let _ = printer.out(Self::from(err));
169 process::exit(EXIT_FAILURE);
170 }
171 }
172 }
173
174 fn sources(&self) -> impl Iterator<Item = String> + '_ {
175 self.error.chain().skip(1).map(ToString::to_string)
176 }
177
178 fn suggestions(&self) -> Option<&str> {
179 if !log_enabled!(Level::Debug) {
180 Some(self.log_level_hint)
181 } else {
182 None
183 }
184 }
185
186 fn backtrace(&self) -> Option<&Backtrace> {
187 let backtrace = self.error.backtrace();
188
189 if let BacktraceStatus::Captured = backtrace.status() {
190 Some(backtrace)
191 } else {
192 None
193 }
194 }
195}
196
197impl<C: ErrorCode> From<Error> for ErrorReport<C> {
198 fn from(error: Error) -> Self {
199 let code = code_of(&error);
200
201 Self {
202 error,
203 code,
204 log_level_hint: "Run with --log-level to enable more verbose logs",
205 }
206 }
207}
208
209impl<C: ErrorCode> fmt::Display for ErrorReport<C> {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 write!(f, "Error: {}", self.error)?;
212
213 let mut header_printed = false;
214 for err in self.sources() {
215 if !header_printed {
216 writeln!(f)?;
217 writeln!(f)?;
218 write!(f, "Caused by:")?;
219 header_printed = true;
220 }
221
222 writeln!(f)?;
223 write!(f, " - {}", err.trim())?;
224 }
225
226 if let Some(backtrace) = self.backtrace() {
227 writeln!(f)?;
228 writeln!(f)?;
229 writeln!(f, "Backtrace:")?;
230 write!(f, "{backtrace}")?;
231 }
232
233 if let Some(suggestion) = self.suggestions() {
234 writeln!(f)?;
235 writeln!(f)?;
236 writeln!(f, "Suggestions:")?;
237 write!(f, " - {suggestion}")?;
238 }
239
240 writeln!(f)
241 }
242}
243
244impl<C: ErrorCode> Serialize for ErrorReport<C> {
245 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
246 let output = ErrorReportOutput {
247 code: self.code.clone(),
248 error: self.error.to_string(),
249 sources: self.sources().collect(),
250 backtrace: self.backtrace().map(ToString::to_string),
251 };
252
253 output.serialize(serializer)
254 }
255}
256
257impl<C: ErrorCode> JsonSchema for ErrorReport<C> {
258 fn schema_name() -> std::borrow::Cow<'static, str> {
259 "ErrorReport".into()
260 }
261
262 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
263 ErrorReportOutput::<C>::json_schema(generator)
264 }
265}
266
267#[derive(Serialize, JsonSchema)]
272#[serde(rename_all = "camelCase")]
273struct ErrorReportOutput<C> {
274 code: Option<C>,
277 error: String,
279 sources: Vec<String>,
281 backtrace: Option<String>,
283}
284
285#[cfg(test)]
286mod tests {
287 use anyhow::{Context, anyhow};
288 use serde::Serialize;
289 use serde_json::json;
290
291 use crate::{clap::commands::json_schema::output_schema, error::*};
292
293 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, JsonSchema)]
294 #[serde(rename_all = "kebab-case")]
295 enum TestCode {
296 BodyPending,
297 }
298
299 fn pending() -> Result<(), Error> {
300 Err(CodedError::new(TestCode::BodyPending, "not downloaded yet").into())
301 }
302
303 #[test]
304 fn a_coded_error_keeps_its_code_under_context() {
305 let err = pending().context("Read message 3").unwrap_err();
306 assert_eq!(code_of(&err), Some(TestCode::BodyPending));
307 }
308
309 #[test]
310 fn the_json_report_carries_the_code_beside_the_message() {
311 let err = pending().unwrap_err();
312 let json = serde_json::to_value(ErrorReport::<TestCode>::from(err)).unwrap();
313
314 assert_eq!(json["code"], "body-pending");
315 assert_eq!(json["error"], "not downloaded yet");
316 }
317
318 #[test]
319 fn an_uncoded_error_prints_a_null_code() {
320 let err = anyhow!("boom").context("Read message 3");
321 let json = serde_json::to_value(ErrorReport::<TestCode>::from(err)).unwrap();
322
323 assert_eq!(
324 json,
325 json!({ "code": null, "error": "Read message 3", "sources": ["boom"], "backtrace": null })
326 );
327 }
328
329 #[test]
330 fn the_schema_types_the_code_by_the_vocabulary() {
331 let schema = output_schema::<ErrorReport<TestCode>>();
332 let required = schema["required"].as_array().unwrap();
333
334 assert!(required.contains(&json!("code")), "{schema}");
335 assert!(required.contains(&json!("error")), "{schema}");
336 assert_eq!(schema["$defs"]["TestCode"]["enum"], json!(["body-pending"]));
337 }
338
339 #[test]
340 fn a_partial_outcome_keeps_its_status_under_context() {
341 let err = Error::from(PartialOutcome::new(3)).context("Check account");
342 assert_eq!(partial_outcome_of(&err).map(|o| o.status()), Some(3));
343 assert_eq!(partial_outcome_of(&anyhow!("boom")), None);
344 }
345
346 #[test]
347 #[should_panic]
348 fn a_partial_outcome_cannot_read_as_a_failure() {
349 PartialOutcome::new(1);
350 }
351}