use std::borrow::Cow;
use std::fmt::{self, Display, Formatter};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(into = "i64", from = "i64")]
pub enum ErrorCode {
ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
ServerError(i64),
RequestCancelled,
ContentModified,
}
impl ErrorCode {
pub const fn code(&self) -> i64 {
match *self {
ErrorCode::ParseError => -32700,
ErrorCode::InvalidRequest => -32600,
ErrorCode::MethodNotFound => -32601,
ErrorCode::InvalidParams => -32602,
ErrorCode::InternalError => -32603,
ErrorCode::RequestCancelled => -32800,
ErrorCode::ContentModified => -32801,
ErrorCode::ServerError(code) => code,
}
}
pub const fn description(&self) -> &'static str {
match *self {
ErrorCode::ParseError => "Parse error",
ErrorCode::InvalidRequest => "Invalid request",
ErrorCode::MethodNotFound => "Method not found",
ErrorCode::InvalidParams => "Invalid params",
ErrorCode::InternalError => "Internal error",
ErrorCode::RequestCancelled => "Canceled",
ErrorCode::ContentModified => "Content modified",
ErrorCode::ServerError(_) => "Server error",
}
}
}
impl From<i64> for ErrorCode {
fn from(code: i64) -> Self {
match code {
-32700 => ErrorCode::ParseError,
-32600 => ErrorCode::InvalidRequest,
-32601 => ErrorCode::MethodNotFound,
-32602 => ErrorCode::InvalidParams,
-32603 => ErrorCode::InternalError,
-32800 => ErrorCode::RequestCancelled,
-32801 => ErrorCode::ContentModified,
code => ErrorCode::ServerError(code),
}
}
}
impl From<ErrorCode> for i64 {
fn from(code: ErrorCode) -> Self {
code.code()
}
}
impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(&self.code(), f)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Error {
pub code: ErrorCode,
pub message: Cow<'static, str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl Error {
pub const fn new(code: ErrorCode) -> Self {
Error {
code,
message: Cow::Borrowed(code.description()),
data: None,
}
}
pub const fn parse_error() -> Self {
Error::new(ErrorCode::ParseError)
}
pub const fn invalid_request() -> Self {
Error::new(ErrorCode::InvalidRequest)
}
pub const fn method_not_found() -> Self {
Error::new(ErrorCode::MethodNotFound)
}
pub fn invalid_params<M>(message: M) -> Self
where
M: Into<Cow<'static, str>>,
{
Error {
code: ErrorCode::InvalidParams,
message: message.into(),
data: None,
}
}
pub const fn internal_error() -> Self {
Error::new(ErrorCode::InternalError)
}
pub const fn request_cancelled() -> Self {
Error::new(ErrorCode::RequestCancelled)
}
pub const fn content_modified() -> Self {
Error::new(ErrorCode::ContentModified)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}: {}", self.code.description(), self.message)
}
}
impl std::error::Error for Error {}
pub(crate) const fn not_initialized_error() -> Error {
Error {
code: ErrorCode::ServerError(-32002),
message: Cow::Borrowed("Server not initialized"),
data: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_code_serializes_as_i64() {
let serialized = serde_json::to_string(&ErrorCode::ParseError).unwrap();
assert_eq!(serialized, "-32700");
let serialized = serde_json::to_string(&ErrorCode::ServerError(-12345)).unwrap();
assert_eq!(serialized, "-12345");
}
#[test]
fn error_code_deserializes_from_i64() {
let deserialized: ErrorCode = serde_json::from_str("-32700").unwrap();
assert_eq!(deserialized, ErrorCode::ParseError);
let deserialized: ErrorCode = serde_json::from_str("-12345").unwrap();
assert_eq!(deserialized, ErrorCode::ServerError(-12345));
}
}