jsonwebtoken/src/errors.rs

69 lines
2.4 KiB
Rust
Raw Normal View History

use std::{string, fmt, error};
2015-10-31 11:37:15 -04:00
use rustc_serialize::{json, base64};
#[derive(Debug)]
2015-11-01 17:59:42 -05:00
/// All the errors we can encounter while signing/verifying tokens
/// and a couple of custom one for when the token we are trying
/// to verify is invalid
2015-10-31 11:37:15 -04:00
pub enum Error {
EncodeJSON(json::EncoderError),
DecodeBase64(base64::FromBase64Error),
DecodeJSON(json::DecoderError),
Utf8(string::FromUtf8Error),
2015-11-01 17:59:42 -05:00
2015-11-01 17:31:46 -05:00
InvalidToken,
2015-11-02 16:22:21 -05:00
InvalidSignature,
WrongAlgorithmHeader
2015-10-31 11:37:15 -04:00
}
macro_rules! impl_from_error {
($f: ty, $e: expr) => {
impl From<$f> for Error {
fn from(f: $f) -> Error { $e(f) }
}
}
}
impl_from_error!(json::EncoderError, Error::EncodeJSON);
impl_from_error!(base64::FromBase64Error, Error::DecodeBase64);
impl_from_error!(json::DecoderError, Error::DecodeJSON);
impl_from_error!(string::FromUtf8Error, Error::Utf8);
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::EncodeJSON(ref err) => err.description(),
Error::DecodeBase64(ref err) => err.description(),
Error::DecodeJSON(ref err) => err.description(),
Error::Utf8(ref err) => err.description(),
Error::InvalidToken => "Invalid Token",
Error::InvalidSignature => "Invalid Signature",
Error::WrongAlgorithmHeader => "Wrong Algorithm Header",
}
}
fn cause(&self) -> Option<&error::Error> {
Some(match *self {
Error::EncodeJSON(ref err) => err as &error::Error,
Error::DecodeBase64(ref err) => err as &error::Error,
Error::DecodeJSON(ref err) => err as &error::Error,
Error::Utf8(ref err) => err as &error::Error,
ref e => e as &error::Error,
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::EncodeJSON(ref err) => fmt::Display::fmt(err, f),
Error::DecodeBase64(ref err) => fmt::Display::fmt(err, f),
Error::DecodeJSON(ref err) => fmt::Display::fmt(err, f),
Error::Utf8(ref err) => fmt::Display::fmt(err, f),
Error::InvalidToken => write!(f, "{}", error::Error::description(self)),
Error::InvalidSignature => write!(f, "{}", error::Error::description(self)),
Error::WrongAlgorithmHeader => write!(f, "{}", error::Error::description(self)),
}
}
}