hatchet_client/task_error.rs
1//! The error a task handler returns.
2
3use std::fmt;
4
5/// Why a task run failed, and whether Hatchet should retry it.
6///
7/// Every automatic conversion into `TaskError` (the blanket
8/// `From<E: std::error::Error>` below) produces a **retryable** error, so a
9/// bare `?` inside a handler is always a bet that retrying might help. Use
10/// [`TaskError::non_retryable`] explicitly when it can't.
11///
12/// `anyhow::Error` does not implement `std::error::Error`, so it does not convert
13/// automatically; convert it explicitly with `TaskError::new(e.to_string())` (or
14/// `TaskError::new(format!("{e:#}"))` to include its context chain).
15///
16/// `TaskError` deliberately does not implement `std::error::Error`: that
17/// would conflict with the blanket `From` conversion.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TaskError {
20 message: String,
21 retryable: bool,
22}
23
24impl TaskError {
25 /// A failure Hatchet may retry, if the task has retries left.
26 pub fn new(message: impl Into<String>) -> Self {
27 Self {
28 message: message.into(),
29 retryable: true,
30 }
31 }
32
33 /// A failure Hatchet must not retry.
34 pub fn non_retryable(message: impl Into<String>) -> Self {
35 Self {
36 message: message.into(),
37 retryable: false,
38 }
39 }
40
41 /// The message reported to the engine.
42 pub fn message(&self) -> &str {
43 &self.message
44 }
45
46 /// Whether Hatchet may retry the task.
47 pub fn is_retryable(&self) -> bool {
48 self.retryable
49 }
50}
51
52impl fmt::Display for TaskError {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 f.write_str(&self.message)
55 }
56}
57
58impl<E: std::error::Error> From<E> for TaskError {
59 fn from(error: E) -> Self {
60 Self::new(error.to_string())
61 }
62}
63
64// `impl From<String> for TaskError`, `impl From<&str> for TaskError`, and
65// `impl From<Box<dyn std::error::Error + Send + Sync>> for TaskError` were
66// all attempted here, as requested, but each one fails to compile with
67// "conflicting implementations of trait `From<...>` for type `TaskError`"
68// against the blanket `impl<E: std::error::Error> From<E> for TaskError`
69// above. None of `String`, `str`, or `Box<dyn std::error::Error + Send +
70// Sync>` implements `std::error::Error` *today*, but Rust's coherence
71// checker rejects a dedicated impl for any of them anyway: since the
72// blanket impl is generic over any `E: std::error::Error` (a foreign
73// trait) for the local type `TaskError`, and `String`/`str`/`Box` are all
74// std types the compiler must treat as potentially gaining an
75// `std::error::Error` impl in a future std version, it conservatively
76// assumes future overlap and refuses to compile either impl. So none of
77// the three are added; use `TaskError::new(message)` for a `String`/`&str`
78// message, and `TaskError::new(error.to_string())` for a
79// `Box<dyn std::error::Error + Send + Sync>`.
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn new_errors_are_retryable() {
87 let error = TaskError::new("flaky network");
88 assert!(error.is_retryable());
89 assert_eq!(error.message(), "flaky network");
90 assert_eq!(error.to_string(), "flaky network");
91 }
92
93 #[test]
94 fn non_retryable_errors_say_so() {
95 let error = TaskError::non_retryable("bad input");
96 assert!(!error.is_retryable());
97 assert_eq!(error.message(), "bad input");
98 }
99
100 #[test]
101 fn question_mark_converts_any_std_error_into_a_retryable_task_error() {
102 fn parse() -> Result<i32, TaskError> {
103 Ok("not a number".parse::<i32>()?)
104 }
105 let error = parse().unwrap_err();
106 assert!(error.is_retryable());
107 assert!(error.message().contains("invalid digit"), "{error}");
108 }
109
110 #[test]
111 fn a_boxed_error_converts_via_new_and_is_retryable() {
112 // `Box<dyn std::error::Error + Send + Sync>` does not itself implement
113 // `std::error::Error` (it is unsized, and std's `Error for Box<E>`
114 // impl requires `E: Sized`), and a dedicated `From` impl for it would
115 // conflict with the blanket impl (see the comment above), so this is
116 // the documented manual conversion instead of a `?`.
117 fn boxed_failure() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
118 "not a number".parse::<i32>()?;
119 Ok(())
120 }
121 fn fails() -> Result<(), TaskError> {
122 boxed_failure().map_err(|e| TaskError::new(e.to_string()))?;
123 Ok(())
124 }
125 let error = fails().unwrap_err();
126 assert!(error.is_retryable());
127 assert!(error.message().contains("invalid digit"), "{error}");
128 }
129}