summaryrefslogtreecommitdiff
path: root/engine-ecs/src/error.rs
blob: 5ce5632bc9d76b51196155688d93aa06013d2d4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::fmt::{Debug, Display};

use crate::World;

#[macro_export]
macro_rules! error {
    ($lit: literal) => {
        $crate::error::Error::message($lit)
    };

    ($lit: literal, $($tt: tt)*) => {
        $crate::error::Error::message(std::format!($lit, $($tt)*))
    };

    ($err: expr) => {
        $crate::error::Error::from($err)
    };
}

pub struct Error
{
    inner: anyhow::Error,
}

impl Error
{
    pub fn new<Err>(err: Err) -> Self
    where
        Err: std::error::Error + Send + Sync + 'static,
    {
        Self::from(err)
    }

    pub fn message<Message>(message: Message) -> Self
    where
        Message: Display + Debug + Send + Sync + 'static,
    {
        Self { inner: anyhow::Error::msg(message) }
    }

    pub fn context<Ctx>(self, context: Ctx) -> Error
    where
        Ctx: Display + Send + Sync + 'static,
    {
        Self { inner: self.inner.context(context) }
    }

    /// Retrieves the message text of a system-defined Windows Win32 error code and
    /// returns it as a `Error`. If this fails (for example if the error code is invalid),
    /// the returned `Error` contains the error code number.
    #[cfg(windows)]
    pub fn from_system_defined_win32_error(error: u32) -> Self
    {
        use std::ffi::CStr;
        use std::ptr::null;

        use windows_sys::Win32::System::Diagnostics::Debug::{
            FormatMessageA,
            FORMAT_MESSAGE_FROM_SYSTEM,
            FORMAT_MESSAGE_IGNORE_INSERTS,
        };

        let mut buffer = vec![0u8; 256];

        let len = unsafe {
            FormatMessageA(
                FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                null(),
                error,
                0,
                buffer.as_mut_ptr(),
                (buffer.len() - 1) as u32,
                null(),
            )
        } as usize;

        if len == 0 {
            return Self::message(format!("Win32 error {error}"));
        }

        let buf = unsafe { CStr::from_bytes_with_nul_unchecked(&buffer[..len + 1]) };

        Self::message(buf.to_string_lossy().trim().to_owned())
    }
}

impl Debug for Error
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        <anyhow::Error as Debug>::fmt(&self.inner, formatter)
    }
}

impl Display for Error
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        <anyhow::Error as Display>::fmt(&self.inner, formatter)
    }
}

impl<Err> From<Err> for Error
where
    Err: std::error::Error + Send + Sync + 'static,
{
    fn from(err: Err) -> Self
    {
        Self { inner: err.into() }
    }
}

pub trait Context<T>
{
    fn context<Ctx>(self, context: Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static;

    fn with_context<Ctx>(self, context_func: impl FnOnce() -> Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static;
}

impl<T, Err> Context<T> for Result<T, Err>
where
    Err: std::error::Error + Send + Sync + 'static,
{
    fn context<Ctx>(self, context: Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static,
    {
        self.map_err(|err| Error::from(err).context(context))
    }

    fn with_context<Ctx>(self, context_func: impl FnOnce() -> Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static,
    {
        self.map_err(|err| Error::from(err).context(context_func()))
    }
}

impl<T> Context<T> for Result<T, Error>
{
    fn context<Ctx>(self, context: Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static,
    {
        self.map_err(|err| err.context(context))
    }

    fn with_context<Ctx>(self, context_func: impl FnOnce() -> Ctx) -> Result<T, Error>
    where
        Ctx: Display + Send + Sync + 'static,
    {
        self.map_err(|err| err.context(context_func()))
    }
}

pub type HandlerFn = fn(&World, Error, Metadata);

/// Error metadata.
#[derive(Debug)]
pub struct Metadata
{
    pub source_name: &'static str,
    pub source_kind: SourceKind,
}

/// Error source kind.
#[derive(Debug)]
#[non_exhaustive]
pub enum SourceKind
{
    System,
    Observer,
}

impl Display for SourceKind
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        match self {
            SourceKind::System => formatter.write_str("system"),
            SourceKind::Observer => formatter.write_str("observer"),
        }
    }
}

pub fn err_handler_panic(_world: &World, err: Error, err_metadata: Metadata)
{
    std::panic::panic_any(err.context(format!(
        "Error occurred in {} '{}'",
        err_metadata.source_kind, err_metadata.source_name
    )));
}

pub fn err_handler_log_error(_world: &World, err: Error, err_metadata: Metadata)
{
    tracing::error!(
        "Error occurred in {} '{}': {err:#}",
        err_metadata.source_kind,
        err_metadata.source_name
    );
}

pub(crate) fn set_panic_hook()
{
    let previous_panic_hook = std::panic::take_hook();

    std::panic::set_hook(Box::new(move |info| {
        let Some(err) = info.payload().downcast_ref::<Error>() else {
            return previous_panic_hook(info);
        };

        print!(
            "Thread '{}' ({:?}) panicked",
            std::thread::current().name().unwrap_or("<unnamed>"),
            get_current_os_thread_id()
        );

        if let Some(location) = info.location() {
            print!(" at {location}");
        }

        print!("\n{err:?}");

        if err.inner.backtrace().status() == std::backtrace::BacktraceStatus::Disabled {
            print!(concat!(
                "\nnote: run with `RUST_BACKTRACE=1` environment variable ",
                "to display a backtrace"
            ));
        }

        println!("");
    }));
}

fn get_current_os_thread_id() -> u64
{
    cfg_select! {
        target_os = "linux" => {
            (unsafe { libc::gettid() }) as u64
        }
        windows => {
            (unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }) as u64
        }
        _ => {
            compile_error!("Unsupported target OS");
        }
    }
}