1use std::cell::RefCell;
4use std::error::Error;
5use std::fmt;
6
7use crate::status;
8
9thread_local! {
10 static MSG_STACK: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
11}
12
13pub fn push_err_msg(msg: impl Into<String>) {
15 MSG_STACK.with(|s| s.borrow_mut().push(msg.into()));
16}
17
18pub fn pop_err_msg() -> Option<String> {
20 MSG_STACK.with(|s| {
21 let mut v = s.borrow_mut();
22 if v.is_empty() {
23 None
24 } else {
25 Some(v.remove(0))
26 }
27 })
28}
29
30pub fn clear_err_msg() {
32 MSG_STACK.with(|s| s.borrow_mut().clear());
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FitsError {
42 pub status: i32,
44 messages: Vec<String>,
45}
46
47impl FitsError {
48 #[must_use]
50 pub fn new(status: i32) -> Self {
51 Self {
52 status,
53 messages: Vec::new(),
54 }
55 }
56
57 #[must_use]
59 pub fn with_message(status: i32, msg: impl Into<String>) -> Self {
60 Self {
61 status,
62 messages: vec![msg.into()],
63 }
64 }
65
66 #[must_use]
68 pub fn status_text(&self) -> &'static str {
69 status::status_text(self.status)
70 }
71
72 #[must_use]
74 pub fn messages(&self) -> &[String] {
75 &self.messages
76 }
77
78 pub fn push_message(&mut self, msg: impl Into<String>) {
80 self.messages.push(msg.into());
81 }
82}
83
84impl fmt::Display for FitsError {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 write!(f, "{} ({})", self.status_text(), self.status)?;
87 for msg in &self.messages {
88 write!(f, ": {msg}")?;
89 }
90 Ok(())
91 }
92}
93
94impl Error for FitsError {}
95
96pub type Result<T> = std::result::Result<T, FitsError>;