use neon;
use serde::{de, ser};
use std::{convert::From, error, fmt, fmt::Display, result};
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
StringTooLong { len: usize },
UnableToCoerce { to_type: &'static str },
EmptyString,
StringTooLongForChar { len: usize },
ExpectingNull,
InvalidKeyType { key: String },
ArrayIndexOutOfBounds { index: u32, length: u32 },
#[doc(hidden)]
NotImplemented { name: &'static str },
Js { throw: neon::result::Throw },
CastError,
Serialize { msg: String },
Deserialize { msg: String },
}
impl error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::StringTooLong { len } => {
"String too long for nodejs len: ".fmt(f)?;
len.fmt(f)
}
Error::UnableToCoerce { to_type } => {
"Unable to coerce value to type: ".fmt(f)?;
to_type.fmt(f)
}
Error::EmptyString => "EmptyString".fmt(f),
Error::StringTooLongForChar { len } => {
"String too long to be a char expected len: 1 got len: ".fmt(f)?;
len.fmt(f)
}
Error::ExpectingNull => "ExpectingNull".fmt(f),
Error::InvalidKeyType { key } => {
"Invalid type of key: '".fmt(f)?;
key.fmt(f)?;
'\''.fmt(f)
}
Error::ArrayIndexOutOfBounds { index, length } => {
"Array index out of bounds (".fmt(f)?;
index.fmt(f)?;
" of ".fmt(f)?;
length.fmt(f)?;
")".fmt(f)
}
Error::NotImplemented { name } => {
"Not implemented: '".fmt(f)?;
name.fmt(f)?;
'\''.fmt(f)
}
Error::Js { throw: _ } => "JS exception".fmt(f),
Error::CastError => "Casting error".fmt(f),
Error::Serialize { msg } => {
"Serialize error: ".fmt(f)?;
msg.fmt(f)
}
Error::Deserialize { msg } => {
"Deserialize error: ".fmt(f)?;
msg.fmt(f)
}
}
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Self::Serialize {
msg: msg.to_string(),
}
}
}
impl de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Self::Deserialize {
msg: msg.to_string(),
}
}
}
impl From<neon::result::Throw> for Error {
fn from(throw: neon::result::Throw) -> Self {
Error::Js { throw }
}
}