use std::fmt;
use jsonx_lib::Value;
use rpc_io::{ErrorCode, ErrorObject};
use crate::error::Error;
#[derive(Clone, Debug, PartialEq)]
pub struct ResponseError {
code: i32,
message: String,
data: Option<Value<'static>>,
}
impl ResponseError {
pub const PARSE_ERROR: i32 = -32700;
pub const INVALID_REQUEST: i32 = -32600;
pub const METHOD_NOT_FOUND: i32 = -32601;
pub const INVALID_PARAMS: i32 = -32602;
pub const INTERNAL_ERROR: i32 = -32603;
pub const SERVER_NOT_INITIALIZED: i32 = -32002;
pub const REQUEST_FAILED: i32 = -32803;
pub const SERVER_CANCELLED: i32 = -32802;
pub const CONTENT_MODIFIED: i32 = -32801;
pub const REQUEST_CANCELLED: i32 = -32800;
#[must_use]
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
}
}
#[must_use]
pub fn with_data(mut self, data: Value<'static>) -> Self {
self.data = Some(data);
self
}
#[inline]
#[must_use]
pub const fn code(&self) -> i32 {
self.code
}
#[inline]
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[inline]
#[must_use]
pub fn data(&self) -> Option<&Value<'static>> {
self.data.as_ref()
}
pub(crate) fn invalid_params(message: impl Into<String>) -> Self {
Self::new(Self::INVALID_PARAMS, message)
}
pub(crate) fn unsupported(what: &str) -> Self {
Self::new(Self::METHOD_NOT_FOUND, format!("unhandled method `{what}`"))
}
}
impl fmt::Display for ResponseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (code {})", self.message, self.code)
}
}
impl std::error::Error for ResponseError {}
impl From<Error> for ResponseError {
fn from(error: Error) -> Self {
Self::new(Self::INTERNAL_ERROR, error.to_string())
}
}
impl From<jsonx_lib::Error> for ResponseError {
fn from(error: jsonx_lib::Error) -> Self {
Self::new(Self::INVALID_PARAMS, format!("invalid params: {error}"))
}
}
impl From<ErrorObject> for ResponseError {
fn from(error: ErrorObject) -> Self {
let code = i32::try_from(error.code().0).unwrap_or(Self::INTERNAL_ERROR);
let mut out = Self::new(code, error.message());
out.data = error
.data()
.and_then(|raw| raw.parse().ok())
.map(Value::into_owned);
out
}
}
impl From<ResponseError> for ErrorObject {
fn from(error: ResponseError) -> Self {
let mut out = ErrorObject::new(ErrorCode(i64::from(error.code)), error.message);
if let Some(data) = error.data {
out = out.with_data(data);
}
out
}
}
#[cfg(test)]
mod tests {
use jsonx_lib::json;
use super::*;
#[test]
fn test_response_error_from_error_is_internal() {
let err = ResponseError::from(Error::Disconnected);
assert_eq!(err.code(), ResponseError::INTERNAL_ERROR);
assert!(!err.message().is_empty());
}
#[test]
fn test_response_error_round_trips_through_the_transport_object() {
let err = ResponseError::new(-32803, "stale").with_data(json!({ "n": 1 }));
let object = ErrorObject::from(err.clone());
assert_eq!(object.code(), ErrorCode(-32803));
assert_eq!(ResponseError::from(object), err);
}
#[test]
fn test_response_error_from_huge_code_is_internal() {
let object = ErrorObject::new(ErrorCode(i64::MAX), "big");
assert_eq!(
ResponseError::from(object).code(),
ResponseError::INTERNAL_ERROR
);
}
#[test]
fn test_response_error_from_json_error_is_invalid_params() {
let err = jsonx_lib::parse("[").err().map(ResponseError::from);
assert_eq!(err.map(|e| e.code()), Some(ResponseError::INVALID_PARAMS));
}
}