use {
crate::protocol::lsp::LSPAny,
serde::{
Deserialize,
Serialize,
},
std::{
borrow::Cow,
fmt::{
self,
Display,
Formatter,
},
},
};
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 {
#[must_use]
pub const fn code(&self) -> i64 {
match *self {
| Self::ParseError => -32700,
| Self::InvalidRequest => -32600,
| Self::MethodNotFound => -32601,
| Self::InvalidParams => -32602,
| Self::InternalError => -32603,
| Self::RequestCancelled => -32800,
| Self::ContentModified => -32801,
| Self::ServerError(code) => code,
}
}
#[must_use]
pub const fn description(&self) -> &'static str {
match *self {
| Self::ParseError => "Parse error",
| Self::InvalidRequest => "Invalid request",
| Self::MethodNotFound => "Method not found",
| Self::InvalidParams => "Invalid params",
| Self::InternalError => "Internal error",
| Self::RequestCancelled => "Canceled",
| Self::ContentModified => "Content modified",
| Self::ServerError(_) => "Server error",
}
}
}
impl From<i64> for ErrorCode {
fn from(code: i64) -> Self {
match code {
| -32700 => Self::ParseError,
| -32600 => Self::InvalidRequest,
| -32601 => Self::MethodNotFound,
| -32602 => Self::InvalidParams,
| -32603 => Self::InternalError,
| -32800 => Self::RequestCancelled,
| -32801 => Self::ContentModified,
| code => Self::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<LSPAny>,
}
impl Error {
#[must_use]
pub const fn new(code: ErrorCode) -> Self {
Self {
code,
message: Cow::Borrowed(code.description()),
data: None,
}
}
#[must_use]
pub const fn parse_error() -> Self {
Self::new(ErrorCode::ParseError)
}
#[must_use]
pub const fn invalid_request() -> Self {
Self::new(ErrorCode::InvalidRequest)
}
#[must_use]
pub const fn method_not_found() -> Self {
Self::new(ErrorCode::MethodNotFound)
}
pub fn invalid_params<M>(message: M) -> Self
where
M: Into<Cow<'static, str>>,
{
Self {
code: ErrorCode::InvalidParams,
message: message.into(),
data: None,
}
}
#[must_use]
pub const fn internal_error() -> Self {
Self::new(ErrorCode::InternalError)
}
#[must_use]
pub const fn request_cancelled() -> Self {
Self::new(ErrorCode::RequestCancelled)
}
#[must_use]
pub const fn content_modified() -> Self {
Self::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 const fn not_initialized_error() -> Error {
Error {
code: ErrorCode::ServerError(-32002),
message: Cow::Borrowed("Request sent before server 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));
}
}