neon/types_impl/extract/
error.rs

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
use std::{convert::Infallible, error, fmt, marker::PhantomData};

use crate::{
    context::{Context, Cx},
    result::JsResult,
    types::{
        extract::{private, TryIntoJs},
        JsError, JsValue, Value,
    },
};

type BoxError = Box<dyn error::Error + Send + Sync + 'static>;

/// Error returned when a JavaScript value is not the type expected
pub struct TypeExpected<T: Value>(PhantomData<T>);

impl<T: Value> TypeExpected<T> {
    pub(super) fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: Value> fmt::Display for TypeExpected<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "expected {}", T::name())
    }
}

impl<T: Value> fmt::Debug for TypeExpected<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("TypeExpected").field(&T::name()).finish()
    }
}

impl<T: Value> error::Error for TypeExpected<T> {}

impl<'cx, T: Value> TryIntoJs<'cx> for TypeExpected<T> {
    type Value = JsError;

    fn try_into_js(self, cx: &mut Cx<'cx>) -> JsResult<'cx, Self::Value> {
        JsError::type_error(cx, self.to_string())
    }
}

impl<T: Value> private::Sealed for TypeExpected<T> {}

impl<'cx> TryIntoJs<'cx> for Infallible {
    type Value = JsValue;

    fn try_into_js(self, _: &mut Cx<'cx>) -> JsResult<'cx, Self::Value> {
        unreachable!()
    }
}

impl private::Sealed for Infallible {}

#[derive(Debug)]
/// Error that implements [`TryIntoJs`] and can produce specific error types.
///
/// [`Error`] implements [`From`] for most error types, allowing ergonomic error handling in
/// exported functions with the `?` operator.
///
/// ### Example
///
/// ```
/// use neon::types::extract::Error;
///
/// #[neon::export]
/// fn read_file(path: String) -> Result<String, Error> {
///     let contents = std::fs::read_to_string(path)?;
///     Ok(contents)
/// }
/// ```
pub struct Error {
    cause: BoxError,
    kind: Option<ErrorKind>,
}

#[derive(Debug)]
enum ErrorKind {
    Error,
    RangeError,
    TypeError,
}

impl Error {
    /// Create a new [`Error`] from a `cause`
    pub fn new<E>(cause: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::create(ErrorKind::Error, cause)
    }

    /// Create a `RangeError`
    pub fn range_error<E>(cause: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::create(ErrorKind::RangeError, cause)
    }

    /// Create a `TypeError`
    pub fn type_error<E>(cause: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::create(ErrorKind::TypeError, cause)
    }

    /// Check if error is a `RangeError`
    pub fn is_range_error(&self) -> bool {
        matches!(self.kind, Some(ErrorKind::RangeError))
    }

    /// Check if error is a `TypeError`
    pub fn is_type_error(&self) -> bool {
        matches!(self.kind, Some(ErrorKind::TypeError))
    }

    /// Get a reference to the underlying `cause`
    pub fn cause(&self) -> &BoxError {
        &self.cause
    }

    /// Extract the `std::error::Error` cause
    pub fn into_cause(self) -> BoxError {
        self.cause
    }

    fn create<E>(kind: ErrorKind, cause: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self {
            cause: cause.into(),
            kind: Some(kind),
        }
    }
}

// Blanket impl allow for ergonomic `?` error handling from typical error types (including `anyhow`)
impl<E> From<E> for Error
where
    E: Into<BoxError>,
{
    fn from(cause: E) -> Self {
        Self::new(cause)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.cause)
    }
}

// N.B.: `TryFromJs` is not included. If Neon were to add support for additional error types,
// this would be a *breaking* change. We will wait for user demand before providing this feature.
impl<'cx> TryIntoJs<'cx> for Error {
    type Value = JsError;

    fn try_into_js(self, cx: &mut Cx<'cx>) -> JsResult<'cx, Self::Value> {
        let message = self.cause.to_string();

        match self.kind {
            Some(ErrorKind::RangeError) => cx.range_error(message),
            Some(ErrorKind::TypeError) => cx.type_error(message),
            _ => cx.error(message),
        }
    }
}