1use std::{
2 error::Error,
3 fmt::{Debug, Display},
4};
5
6use lsp_server::{ErrorCode, ExtractError};
7
8pub trait AsLspError: std::error::Error {
9 fn code(&self) -> ErrorCode {
10 ErrorCode::UnknownErrorCode
11 }
12}
13
14pub struct LspError(Box<dyn AsLspError>);
15
16impl LspError {
17 pub fn code(&self) -> ErrorCode {
18 self.0.code()
19 }
20}
21
22impl Debug for LspError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 Debug::fmt(&self.0, f)
25 }
26}
27
28impl Display for LspError {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 Display::fmt(&self.0, f)
31 }
32}
33
34impl Error for LspError {}
35
36impl<T: AsLspError + 'static> From<T> for LspError {
37 fn from(value: T) -> Self {
38 Self(Box::new(value))
39 }
40}
41
42pub type LspResult<T> = std::result::Result<T, LspError>;
43
44impl AsLspError for ExtractError<lsp_server::Request> {
45 fn code(&self) -> ErrorCode {
46 match self {
47 ExtractError::MethodMismatch(_) => ErrorCode::InternalError,
48 ExtractError::JsonError { .. } => ErrorCode::InvalidParams,
49 }
50 }
51}
52
53impl AsLspError for serde_json::Error {
54 fn code(&self) -> ErrorCode {
55 ErrorCode::InternalError
56 }
57}
58
59pub struct LspErrorString(pub String, pub ErrorCode);
60
61impl AsLspError for LspErrorString {
62 fn code(&self) -> ErrorCode {
63 self.1
64 }
65}
66
67impl Error for LspErrorString {}
68
69impl Debug for LspErrorString {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 Debug::fmt(&self.0, f)
72 }
73}
74
75impl Display for LspErrorString {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 Debug::fmt(&self.0, f)
78 }
79}