1use thiserror::Error;
16
17pub type Result<T> = std::result::Result<T, PlotError>;
19
20#[derive(Debug, Clone, PartialEq, Error)]
22#[non_exhaustive]
23pub enum PlotError {
24 #[error("invalid range [{min}, {max}]: {message}. suggestion: {suggestion}")]
25 InvalidRange {
26 min: f64,
27 max: f64,
28 message: &'static str,
29 suggestion: &'static str,
30 },
31
32 #[error("log scale rejected non-positive bound {value}. suggestion: {suggestion}")]
33 LogScaleNonPositive {
34 value: f64,
35 suggestion: &'static str,
36 },
37
38 #[error("empty figure cannot be rendered. suggestion: {suggestion}")]
39 EmptyFigure { suggestion: &'static str },
40
41 #[error("unsupported output format for path `{path}`. suggestion: {suggestion}")]
42 UnsupportedFormat {
43 path: String,
44 suggestion: &'static str,
45 },
46
47 #[error("I/O error: {message}. suggestion: {suggestion}")]
48 Io {
49 message: String,
50 suggestion: &'static str,
51 },
52
53 #[error("render error: {message}. suggestion: {suggestion}")]
54 Render {
55 message: String,
56 suggestion: &'static str,
57 },
58
59 #[error("text layout error: {message}. suggestion: {suggestion}")]
60 Text {
61 message: String,
62 suggestion: &'static str,
63 },
64
65 #[error("x/y length mismatch: x={x_len}, y={y_len}. suggestion: {suggestion}")]
66 LengthMismatch {
67 x_len: usize,
68 y_len: usize,
69 suggestion: &'static str,
70 },
71
72 #[error(
73 "heatmap size mismatch: expected {expected} values (nrows*ncols={nrows}*{ncols}), got {got}. suggestion: {suggestion}"
74 )]
75 HeatmapSizeMismatch {
76 nrows: usize,
77 ncols: usize,
78 expected: usize,
79 got: usize,
80 suggestion: &'static str,
81 },
82
83 #[error("column `{name}` not found. suggestion: {suggestion}")]
84 ColumnNotFound {
85 name: String,
86 suggestion: &'static str,
87 },
88
89 #[error("column `{name}` is not numeric (dtype={dtype}). suggestion: {suggestion}")]
90 ColumnNotNumeric {
91 name: String,
92 dtype: String,
93 suggestion: &'static str,
94 },
95
96 #[error("external LaTeX unavailable: {message}. suggestion: {suggestion}")]
97 LatexUnavailable {
98 message: String,
99 suggestion: &'static str,
100 },
101
102 #[error("external LaTeX failed: {message}. suggestion: {suggestion}")]
103 LatexFailed {
104 message: String,
105 suggestion: &'static str,
106 },
107
108 #[error("external tool `{tool}` unavailable: {message}. suggestion: {suggestion}")]
109 ExternalToolUnavailable {
110 tool: &'static str,
111 message: String,
112 suggestion: &'static str,
113 },
114
115 #[error("external tool `{tool}` failed: {message}. suggestion: {suggestion}")]
116 ExternalToolFailed {
117 tool: &'static str,
118 message: String,
119 suggestion: &'static str,
120 },
121}
122
123impl PlotError {
124 pub fn invalid_range(min: f64, max: f64) -> Self {
125 Self::InvalidRange {
126 min,
127 max,
128 message: "min must be strictly less than max",
129 suggestion: "swap the bounds or widen the interval so max > min",
130 }
131 }
132
133 pub fn log_non_positive(value: f64) -> Self {
134 Self::LogScaleNonPositive {
135 value,
136 suggestion: "use ScaleType::Symlog, or filter/clip values so the domain is > 0",
137 }
138 }
139
140 pub fn empty_figure() -> Self {
141 Self::EmptyFigure {
142 suggestion:
143 "call Figure::axes(|ax| { ... }) or Figure::subplots(...) before save/render",
144 }
145 }
146
147 pub fn unsupported_format(path: impl Into<String>) -> Self {
148 Self::UnsupportedFormat {
149 path: path.into(),
150 suggestion:
151 "use a path ending in .png, .svg, .pdf, .eps, or .pgf (enable eps/mp4 features when needed)",
152 }
153 }
154
155 pub fn io(message: impl Into<String>) -> Self {
156 Self::Io {
157 message: message.into(),
158 suggestion: "check that the parent directory exists and is writable",
159 }
160 }
161
162 pub fn render(message: impl Into<String>) -> Self {
163 Self::Render {
164 message: message.into(),
165 suggestion: "verify figure size, DPI, and that all axes have valid ranges",
166 }
167 }
168
169 pub fn text(message: impl Into<String>) -> Self {
170 Self::Text {
171 message: message.into(),
172 suggestion: "ensure the embedded font loaded; file a bug if this persists in CI",
173 }
174 }
175
176 pub fn length_mismatch(x_len: usize, y_len: usize) -> Self {
177 Self::LengthMismatch {
178 x_len,
179 y_len,
180 suggestion: "ensure x and y (and yerr for errorbar) have the same length",
181 }
182 }
183
184 pub fn heatmap_size_mismatch(nrows: usize, ncols: usize, got: usize) -> Self {
185 Self::HeatmapSizeMismatch {
186 nrows,
187 ncols,
188 expected: nrows.saturating_mul(ncols),
189 got,
190 suggestion: "pass a flat row-major slice with length nrows * ncols",
191 }
192 }
193
194 pub fn column_not_found(name: impl Into<String>) -> Self {
195 Self::ColumnNotFound {
196 name: name.into(),
197 suggestion: "check the column name (case-sensitive) or print df.get_column_names()",
198 }
199 }
200
201 pub fn column_not_numeric(name: impl Into<String>, dtype: impl Into<String>) -> Self {
202 Self::ColumnNotNumeric {
203 name: name.into(),
204 dtype: dtype.into(),
205 suggestion: "cast the column to a numeric dtype (e.g. Float64 / Int64) before plotting",
206 }
207 }
208
209 pub fn latex_unavailable(message: impl Into<String>) -> Self {
210 Self::LatexUnavailable {
211 message: message.into(),
212 suggestion: "install TeX Live or MiKTeX and ensure `latex` and `dvipng` are on PATH; or omit Figure::usetex(true) / disable feature \"latex\" to use built-in mathtext",
213 }
214 }
215
216 pub fn latex_failed(message: impl Into<String>) -> Self {
217 Self::LatexFailed {
218 message: message.into(),
219 suggestion: "inspect the LaTeX log in the error message; simplify the formula / preamble; or disable usetex to use built-in mathtext",
220 }
221 }
222
223 pub fn external_tool_unavailable(tool: &'static str, message: impl Into<String>) -> Self {
224 let suggestion = match tool {
225 "ffmpeg" => {
226 "install ffmpeg and ensure it is on PATH; or use Animation::save_gif / save_png_sequence"
227 }
228 "gs" | "gswin64c" | "gswin32c" => {
229 "install Ghostscript and ensure `gs` (or gswin64c on Windows) is on PATH; or save as .pdf/.svg instead"
230 }
231 _ => "install the required external tool and ensure it is on PATH",
232 };
233 Self::ExternalToolUnavailable {
234 tool,
235 message: message.into(),
236 suggestion,
237 }
238 }
239
240 pub fn external_tool_failed(tool: &'static str, message: impl Into<String>) -> Self {
241 Self::ExternalToolFailed {
242 tool,
243 message: message.into(),
244 suggestion:
245 "inspect the tool stderr in the error message; verify input paths and permissions",
246 }
247 }
248
249 pub fn suggestion(&self) -> &str {
251 match self {
252 Self::InvalidRange { suggestion, .. }
253 | Self::LogScaleNonPositive { suggestion, .. }
254 | Self::EmptyFigure { suggestion }
255 | Self::UnsupportedFormat { suggestion, .. }
256 | Self::Io { suggestion, .. }
257 | Self::Render { suggestion, .. }
258 | Self::Text { suggestion, .. }
259 | Self::LengthMismatch { suggestion, .. }
260 | Self::HeatmapSizeMismatch { suggestion, .. }
261 | Self::ColumnNotFound { suggestion, .. }
262 | Self::ColumnNotNumeric { suggestion, .. }
263 | Self::LatexUnavailable { suggestion, .. }
264 | Self::LatexFailed { suggestion, .. }
265 | Self::ExternalToolUnavailable { suggestion, .. }
266 | Self::ExternalToolFailed { suggestion, .. } => suggestion,
267 }
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn every_constructor_has_nonempty_suggestion() {
277 let samples = [
278 PlotError::invalid_range(1.0, 0.0),
279 PlotError::log_non_positive(-3.0),
280 PlotError::empty_figure(),
281 PlotError::unsupported_format("out.jpg"),
282 PlotError::io("disk full"),
283 PlotError::render("bad pixmap"),
284 PlotError::text("font lock"),
285 PlotError::length_mismatch(3, 2),
286 PlotError::heatmap_size_mismatch(2, 2, 3),
287 PlotError::column_not_found("x"),
288 PlotError::column_not_numeric("y", "String"),
289 PlotError::latex_unavailable("latex not on PATH"),
290 PlotError::latex_failed("dvipng exit 1"),
291 PlotError::external_tool_unavailable("ffmpeg", "not on PATH"),
292 PlotError::external_tool_failed("gs", "exit 1"),
293 ];
294 for err in samples {
295 let s = err.suggestion();
296 assert!(!s.is_empty(), "empty suggestion for {err}");
297 assert!(s.len() >= 10, "suggestion too vague for {err}: {s:?}");
298 let display = err.to_string();
299 assert!(
300 display.contains("suggestion:"),
301 "Display should include suggestion: {display}"
302 );
303 }
304 }
305}