1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
//! # JSON RPC module errors

use super::core;
use hex;
use jsonrpc_core;
use keystore;
use reqwest;
use rustc_serialize;
use serde_json;
use std::{error, fmt, io};

/// JSON RPC errors
#[derive(Debug)]
pub enum Error {
    /// Http client error
    HttpClient(reqwest::Error),
    /// RPC error
    RPC(jsonrpc_core::Error),
    /// Invalid data format
    InvalidDataFormat(String),
}

impl From<rustc_serialize::json::EncoderError> for Error {
    fn from(err: rustc_serialize::json::EncoderError) -> Self {
        Error::InvalidDataFormat(format!("decoder: {}", err.to_string()))
    }
}

impl From<rustc_serialize::json::DecoderError> for Error {
    fn from(err: rustc_serialize::json::DecoderError) -> Self {
        Error::InvalidDataFormat(format!("decoder: {}", err.to_string()))
    }
}

impl From<keystore::Error> for Error {
    fn from(err: keystore::Error) -> Self {
        Error::InvalidDataFormat(format!("keystore: {}", err.to_string()))
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Error::InvalidDataFormat(e.to_string())
    }
}

impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Error::HttpClient(err)
    }
}

impl From<core::Error> for Error {
    fn from(err: core::Error) -> Self {
        Error::InvalidDataFormat(err.to_string())
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::InvalidDataFormat(err.to_string())
    }
}

impl From<hex::FromHexError> for Error {
    fn from(err: hex::FromHexError) -> Self {
        Error::InvalidDataFormat(err.to_string())
    }
}

impl From<jsonrpc_core::Error> for Error {
    fn from(err: jsonrpc_core::Error) -> Self {
        Error::RPC(err)
    }
}

impl Into<jsonrpc_core::Error> for Error {
    fn into(self) -> jsonrpc_core::Error {
        jsonrpc_core::Error::internal_error()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::HttpClient(ref err) => write!(f, "HTTP client error: {}", err),
            Error::RPC(ref err) => write!(f, "RPC error: {:?}", err),
            Error::InvalidDataFormat(ref str) => write!(f, "Invalid data format: {}", str),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        "JSON RPC errors"
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::HttpClient(ref err) => Some(err),
            _ => None,
        }
    }
}