sui_sdk/
json_rpc_error.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3use jsonrpsee::types::error::UNKNOWN_ERROR_CODE;
4pub use sui_json_rpc_api::{TRANSACTION_EXECUTION_CLIENT_ERROR_CODE, TRANSIENT_ERROR_CODE};
5use thiserror::Error;
6
7#[derive(Error, Debug, Clone)]
8pub struct Error {
9    pub code: i32,
10    pub message: String,
11    // TODO: as this SDK is specialized for the Sui JSON RPC implementation, we should define structured representation for the data field if applicable
12    pub data: Option<serde_json::Value>,
13}
14
15impl std::fmt::Display for Error {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        write!(f, "code: '{}', message: '{}'", self.code, self.message)
18    }
19}
20
21impl Error {
22    pub fn is_call_error(&self) -> bool {
23        self.code != UNKNOWN_ERROR_CODE
24    }
25
26    pub fn is_client_error(&self) -> bool {
27        use jsonrpsee::types::error::{
28            BATCHES_NOT_SUPPORTED_CODE, INVALID_PARAMS_CODE, INVALID_REQUEST_CODE,
29            METHOD_NOT_FOUND_CODE, OVERSIZED_REQUEST_CODE, PARSE_ERROR_CODE,
30        };
31        matches!(
32            self.code,
33            PARSE_ERROR_CODE
34                | OVERSIZED_REQUEST_CODE
35                | INVALID_PARAMS_CODE
36                | INVALID_REQUEST_CODE
37                | METHOD_NOT_FOUND_CODE
38                | BATCHES_NOT_SUPPORTED_CODE
39                | TRANSACTION_EXECUTION_CLIENT_ERROR_CODE
40        )
41    }
42
43    pub fn is_execution_error(&self) -> bool {
44        self.code == TRANSACTION_EXECUTION_CLIENT_ERROR_CODE
45    }
46
47    pub fn is_transient_error(&self) -> bool {
48        self.code == TRANSIENT_ERROR_CODE
49    }
50}
51
52impl From<jsonrpsee::core::ClientError> for Error {
53    fn from(err: jsonrpsee::core::ClientError) -> Self {
54        // The following code relies on jsonrpsee's From<Error> for ErrorObjectOwned implementation
55        // It converts any variant that is not Error::Call into an ErrorObject with UNKNOWN_ERROR_CODE
56        let error_object_owned = match err {
57            jsonrpsee::core::ClientError::Call(e) => e,
58            _ => jsonrpsee::types::error::ErrorCode::from(UNKNOWN_ERROR_CODE).into(),
59        };
60        Error {
61            code: error_object_owned.code(),
62            message: error_object_owned.message().to_string(),
63            data: None,
64        }
65    }
66}