use std::fmt;
use crate::Error;
pub struct FunctionError {
kind: Kind,
}
#[cfg_attr(
not(any(
feature = "boa",
feature = "quickjs",
feature = "v8",
feature = "fuzzing",
test
)),
allow(dead_code, reason = "only the host bridge calls methods")
)]
enum Kind {
Application {
message: String,
code: Option<String>,
},
Arguments(String),
Host(Error),
Panicked,
}
impl FunctionError {
pub fn new(message: impl Into<String>) -> Self {
Self {
kind: Kind::Application {
message: message.into(),
code: None,
},
}
}
pub fn code(mut self, code: impl Into<String>) -> Self {
if let Kind::Application { code: slot, .. } = &mut self.kind {
*slot = Some(code.into());
}
self
}
pub(super) fn arguments(detail: String) -> Self {
Self {
kind: Kind::Arguments(detail),
}
}
}
#[cfg(any(
feature = "boa",
feature = "quickjs",
feature = "v8",
feature = "fuzzing",
test
))]
impl FunctionError {
pub(crate) fn panicked() -> Self {
Self {
kind: Kind::Panicked,
}
}
pub(crate) fn describe(&self) -> serde_json::Value {
match &self.kind {
Kind::Application { message, code } => {
serde_json::json!({ "kind": "application", "code": code, "message": message })
}
Kind::Arguments(_) => {
serde_json::json!({ "kind": "arguments", "code": "INVALID_ARGUMENTS", "message": "invalid arguments" })
}
Kind::Host(error) => {
serde_json::json!({ "code": error.code(), "message": error.guest_message() })
}
Kind::Panicked => {
serde_json::json!({ "code": "PANICKED", "message": "host function panicked" })
}
}
}
}
impl From<Error> for FunctionError {
fn from(error: Error) -> Self {
Self {
kind: Kind::Host(error),
}
}
}
impl fmt::Display for FunctionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
Kind::Application {
message,
code: Some(code),
} => write!(formatter, "{code}: {message}"),
Kind::Application { message, .. } => formatter.write_str(message),
Kind::Arguments(detail) => write!(formatter, "invalid arguments: {detail}"),
Kind::Host(error) => error.fmt(formatter),
Kind::Panicked => formatter.write_str("host function panicked"),
}
}
}
impl fmt::Debug for FunctionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "FunctionError({self})")
}
}
impl std::error::Error for FunctionError {}