use alloc::{borrow::Cow, format, string::String};
use core::fmt;
use crate::{
raw::{Json, Raw},
text,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ErrorCode(pub i64);
impl ErrorCode {
pub const PARSE_ERROR: ErrorCode = ErrorCode(-32700);
pub const INVALID_REQUEST: ErrorCode = ErrorCode(-32600);
pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode(-32601);
pub const INVALID_PARAMS: ErrorCode = ErrorCode(-32602);
pub const INTERNAL_ERROR: ErrorCode = ErrorCode(-32603);
pub const SERVER_OVERLOADED: ErrorCode = ErrorCode(-32000);
pub const SERVER_NOT_INITIALIZED: ErrorCode = ErrorCode(-32002);
pub const REQUEST_CANCELLED: ErrorCode = ErrorCode(-32800);
#[must_use]
pub const fn name(self) -> Option<&'static str> {
Some(match self.0 {
-32700 => "parse error",
-32600 => "invalid request",
-32601 => "method not found",
-32602 => "invalid params",
-32603 => "internal error",
-32000 => "server overloaded",
-32002 => "server not initialized",
-32800 => "request cancelled",
_ => return None,
})
}
#[must_use]
pub const fn is_reserved(self) -> bool {
self.0 >= -32768 && self.0 <= -32000
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => write!(f, "{} ({name})", self.0),
None => write!(f, "{}", self.0),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ErrorObject {
code: ErrorCode,
message: Cow<'static, str>,
data: Option<Raw<'static>>,
}
impl ErrorObject {
#[must_use]
pub fn new(code: ErrorCode, message: impl Into<Cow<'static, str>>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
#[must_use]
pub fn with_data<'a>(mut self, data: impl Into<Json<'a>>) -> Self {
self.data = Some(data.into().into_raw());
self
}
#[must_use]
pub fn parse_error(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorCode::PARSE_ERROR, message)
}
#[must_use]
pub fn invalid_request(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorCode::INVALID_REQUEST, message)
}
#[must_use]
pub fn method_not_found(method: &str) -> Self {
Self::new(
ErrorCode::METHOD_NOT_FOUND,
format!("method not found: `{}`", clip(method)),
)
}
#[must_use]
pub fn invalid_params(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorCode::INVALID_PARAMS, message)
}
#[must_use]
pub fn internal_error(message: impl Into<Cow<'static, str>>) -> Self {
Self::new(ErrorCode::INTERNAL_ERROR, message)
}
#[inline]
#[must_use]
pub const fn code(&self) -> ErrorCode {
self.code
}
#[inline]
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[inline]
#[must_use]
pub fn data(&self) -> Option<&Raw<'static>> {
self.data.as_ref()
}
pub(crate) fn from_parts(code: i64, message: String, data: Option<Raw<'static>>) -> Self {
Self {
code: ErrorCode(code),
message: Cow::Owned(message),
data,
}
}
pub(crate) fn write(&self, out: &mut String) {
out.push_str("{\"code\":");
text::push_i64(out, self.code.0);
out.push_str(",\"message\":");
jsonx_lib::write_string(out, &self.message);
if let Some(data) = &self.data {
out.push_str(",\"data\":");
out.push_str(data.as_str());
}
out.push('}');
}
}
impl fmt::Display for ErrorObject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (code {})", self.message, self.code.0)
}
}
impl core::error::Error for ErrorObject {}
impl From<jsonx_lib::Error> for ErrorObject {
fn from(error: jsonx_lib::Error) -> Self {
Self::invalid_params(format!("invalid params: {error}"))
}
}
pub(crate) fn clip(text: &str) -> Cow<'_, str> {
const MAX: usize = 128;
if text.len() <= MAX {
return Cow::Borrowed(text);
}
let mut end = MAX;
while !text.is_char_boundary(end) {
end -= 1;
}
Cow::Owned(format!("{}\u{2026}", &text[..end]))
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use alloc::string::ToString;
use super::*;
#[test]
fn test_write_with_and_without_data() {
let mut out = String::new();
ErrorObject::new(ErrorCode(-1), "a\"b").write(&mut out);
assert_eq!(out, r#"{"code":-1,"message":"a\"b"}"#);
out.clear();
ErrorObject::internal_error("x")
.with_data(jsonx_lib::json!([1]))
.write(&mut out);
assert_eq!(out, r#"{"code":-32603,"message":"x","data":[1]}"#);
}
#[test]
fn test_clip_respects_char_boundaries() {
let long = "é".repeat(100);
let clipped = clip(&long);
assert!(clipped.len() <= 128 + '\u{2026}'.len_utf8());
assert!(clipped.ends_with('\u{2026}'));
assert_eq!(clip("short"), "short");
}
#[test]
fn test_from_jsonx_error_is_invalid_params() {
let Err(e) = jsonx_lib::parse("[") else {
panic!("`[` must not parse")
};
let error = ErrorObject::from(e);
assert_eq!(error.code(), ErrorCode::INVALID_PARAMS);
assert!(error.message().starts_with("invalid params: "));
assert_eq!(
error.to_string(),
alloc::format!("{} (code -32602)", error.message())
);
}
}