Skip to main content

nadir/
error.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The error type of the `nadir` facade.
16
17use std::fmt;
18
19use nadir_platform::PlatformError;
20use nadir_render::RenderError;
21
22/// Errors that end [`App::run`](crate::App::run).
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Error {
25    /// The window could not be opened.
26    Platform(PlatformError),
27    /// The renderer could not start, or a frame could not be drawn or
28    /// shown.
29    Render(RenderError),
30}
31
32impl fmt::Display for Error {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Platform(error) => write!(f, "could not open the window: {error}"),
36            Self::Render(error) => write!(f, "could not draw: {error}"),
37        }
38    }
39}
40
41impl std::error::Error for Error {
42    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
43        match self {
44            Self::Platform(error) => Some(error),
45            Self::Render(error) => Some(error),
46        }
47    }
48}
49
50impl From<RenderError> for Error {
51    fn from(error: RenderError) -> Self {
52        Self::Render(error)
53    }
54}
55
56impl From<nadir_gfx::GfxError> for Error {
57    fn from(error: nadir_gfx::GfxError) -> Self {
58        Self::Render(RenderError::Gfx(error))
59    }
60}
61
62impl From<PlatformError> for Error {
63    fn from(error: PlatformError) -> Self {
64        Self::Platform(error)
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use std::error::Error as _;
71
72    use super::*;
73
74    #[test]
75    fn a_platform_error_says_what_failed_and_why() {
76        let error = Error::from(PlatformError::Unsupported);
77        assert_eq!(
78            error.to_string(),
79            "could not open the window: this operating system has no backend yet"
80        );
81        let source = error.source().map(ToString::to_string);
82        assert_eq!(
83            source.as_deref(),
84            Some("this operating system has no backend yet")
85        );
86    }
87
88    #[test]
89    fn a_render_error_says_it_could_not_draw() {
90        let error = Error::from(nadir_gfx::GfxError::ContextLost);
91        assert!(error.to_string().starts_with("could not draw: "), "{error}");
92        assert!(error.source().is_some());
93    }
94}