Skip to main content

fetchlet/host/function/
error.rs

1use std::fmt;
2
3use crate::Error;
4
5/// The failure of a [`Functions`](super::Functions) method.
6///
7/// [`FunctionError::new`] reaches JavaScript as an `Error` with its message
8/// and, with [`code`](Self::code), its `code` property. A fetchlet [`Error`]
9/// reaches JavaScript with its generic code and message only, as other host
10/// operations report it, so its detail stays in Rust.
11pub struct FunctionError {
12    kind: Kind,
13}
14
15#[cfg_attr(
16    not(any(
17        feature = "boa",
18        feature = "quickjs",
19        feature = "v8",
20        feature = "fuzzing",
21        test
22    )),
23    allow(dead_code, reason = "only the host bridge calls methods")
24)]
25enum Kind {
26    Application {
27        message: String,
28        code: Option<String>,
29    },
30    /// The arguments did not deserialize; the detail stays in Rust.
31    Arguments(String),
32    Host(Error),
33    Panicked,
34}
35
36impl FunctionError {
37    /// An error JavaScript receives with `message`.
38    pub fn new(message: impl Into<String>) -> Self {
39        Self {
40            kind: Kind::Application {
41                message: message.into(),
42                code: None,
43            },
44        }
45    }
46
47    /// Set the error's `code` property in JavaScript. A fetchlet error
48    /// keeps its own code.
49    pub fn code(mut self, code: impl Into<String>) -> Self {
50        if let Kind::Application { code: slot, .. } = &mut self.kind {
51            *slot = Some(code.into());
52        }
53        self
54    }
55
56    /// Arguments that did not deserialize, which JavaScript receives as a
57    /// `TypeError` naming the method.
58    pub(super) fn arguments(detail: String) -> Self {
59        Self {
60            kind: Kind::Arguments(detail),
61        }
62    }
63}
64
65#[cfg(any(
66    feature = "boa",
67    feature = "quickjs",
68    feature = "v8",
69    feature = "fuzzing",
70    test
71))]
72impl FunctionError {
73    pub(crate) fn panicked() -> Self {
74        Self {
75            kind: Kind::Panicked,
76        }
77    }
78
79    /// The error as the bridge sends it: `kind` tells JavaScript which
80    /// error to build, with fetchlet errors as other host errors are.
81    pub(crate) fn describe(&self) -> serde_json::Value {
82        match &self.kind {
83            Kind::Application { message, code } => {
84                serde_json::json!({ "kind": "application", "code": code, "message": message })
85            }
86            Kind::Arguments(_) => {
87                serde_json::json!({ "kind": "arguments", "code": "INVALID_ARGUMENTS", "message": "invalid arguments" })
88            }
89            Kind::Host(error) => {
90                serde_json::json!({ "code": error.code(), "message": error.guest_message() })
91            }
92            Kind::Panicked => {
93                serde_json::json!({ "code": "PANICKED", "message": "host function panicked" })
94            }
95        }
96    }
97}
98
99impl From<Error> for FunctionError {
100    fn from(error: Error) -> Self {
101        Self {
102            kind: Kind::Host(error),
103        }
104    }
105}
106
107impl fmt::Display for FunctionError {
108    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match &self.kind {
110            Kind::Application {
111                message,
112                code: Some(code),
113            } => write!(formatter, "{code}: {message}"),
114            Kind::Application { message, .. } => formatter.write_str(message),
115            Kind::Arguments(detail) => write!(formatter, "invalid arguments: {detail}"),
116            Kind::Host(error) => error.fmt(formatter),
117            Kind::Panicked => formatter.write_str("host function panicked"),
118        }
119    }
120}
121
122impl fmt::Debug for FunctionError {
123    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124        write!(formatter, "FunctionError({self})")
125    }
126}
127
128impl std::error::Error for FunctionError {}