rquickjs_serde/
err.rs

1use std::{error, fmt};
2
3use rquickjs::Error as JSError;
4use serde::{de, ser};
5
6/// This type represents all possible errors that can occur when serializing or
7/// deserializing JS values.
8pub struct Error(Box<ErrorImpl>);
9
10impl Error {
11    pub(crate) fn new(msg: impl Into<ErrorImpl>) -> Self {
12        Error(Box::new(msg.into()))
13    }
14}
15
16/// Alias for a `Result` with the error type `rquickjs_serde::Error`.
17pub type Result<T> = std::result::Result<T, Error>;
18
19impl fmt::Debug for Error {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        write!(f, "Error({})", self.0)
22    }
23}
24
25impl error::Error for Error {}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29        fmt::Display::fmt(&*self.0, f)
30    }
31}
32
33impl de::Error for Error {
34    fn custom<T: fmt::Display>(msg: T) -> Self {
35        Error(Box::new(ErrorImpl::Message(msg.to_string())))
36    }
37}
38
39impl ser::Error for Error {
40    fn custom<T: fmt::Display>(msg: T) -> Self {
41        Error(Box::new(ErrorImpl::Message(msg.to_string())))
42    }
43}
44
45/// The internal representation of an error.
46///
47/// This enum represents various errors that can occur during JS value serialization or deserialization,
48/// including UTF-8 conversion errors, and errors originating from the `rquickjs` library.
49#[derive(Debug)]
50pub enum ErrorImpl {
51    /// A generic error message
52    Message(String),
53    /// An error originating from the `rquickjs` library.
54    Rquickjs(JSError),
55}
56
57impl fmt::Display for ErrorImpl {
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        match self {
60            ErrorImpl::Message(msg) => write!(f, "{msg}"),
61            ErrorImpl::Rquickjs(e) => write!(f, "{e}"),
62        }
63    }
64}
65
66impl From<&str> for ErrorImpl {
67    fn from(value: &str) -> Self {
68        ErrorImpl::Message(value.to_string())
69    }
70}
71
72impl From<JSError> for ErrorImpl {
73    fn from(value: JSError) -> Self {
74        ErrorImpl::Rquickjs(value)
75    }
76}