1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/src/error.rs

717 lines
23 KiB
Rust
Raw Normal View History

2017-11-20 04:26:31 +01:00
//! Error and Result module
2017-12-02 23:58:22 +01:00
use std::{io, fmt, result};
2017-10-07 06:48:14 +02:00
use std::str::Utf8Error;
use std::string::FromUtf8Error;
2017-11-16 07:06:28 +01:00
use std::io::Error as IoError;
2017-10-07 06:48:14 +02:00
2017-11-24 19:28:43 +01:00
#[cfg(actix_nightly)]
use std::error::Error as StdError;
use cookie;
2017-10-07 06:48:14 +02:00
use httparse;
2017-11-16 07:06:28 +01:00
use failure::Fail;
2017-12-21 05:30:54 +01:00
use futures::Canceled;
2017-11-16 07:06:28 +01:00
use http2::Error as Http2Error;
use http::{header, StatusCode, Error as HttpError};
2017-12-01 04:01:25 +01:00
use http::uri::InvalidUriBytes;
2017-11-16 07:06:28 +01:00
use http_range::HttpRangeParseError;
use serde_json::error::Error as JsonError;
2017-12-07 01:26:27 +01:00
use url::ParseError as UrlParseError;
2017-11-16 07:06:28 +01:00
// re-exports
pub use cookie::{ParseError as CookieParseError};
2017-10-07 06:48:14 +02:00
2017-10-24 08:25:32 +02:00
use body::Body;
2017-11-16 07:06:28 +01:00
use httpresponse::HttpResponse;
2017-11-20 04:51:14 +01:00
use httpcodes::{HTTPBadRequest, HTTPMethodNotAllowed, HTTPExpectationFailed};
2017-10-07 06:48:14 +02:00
2017-11-16 07:06:28 +01:00
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
2017-11-20 04:26:31 +01:00
/// for actix web operations
2017-11-16 07:06:28 +01:00
///
/// This typedef is generally used to avoid writing out `actix_web::error::Error` directly and
/// is otherwise a direct mapping to `Result`.
2017-12-04 03:15:09 +01:00
pub type Result<T, E=Error> = result::Result<T, E>;
2017-11-27 02:30:35 +01:00
/// General purpose actix web error
#[derive(Fail, Debug)]
2017-11-16 07:06:28 +01:00
pub struct Error {
cause: Box<ResponseError>,
2017-11-16 07:06:28 +01:00
}
2017-11-20 04:26:31 +01:00
impl Error {
/// Returns a reference to the underlying cause of this Error.
// this should return &Fail but needs this https://github.com/rust-lang/rust/issues/5665
pub fn cause(&self) -> &ResponseError {
2017-11-20 04:26:31 +01:00
self.cause.as_ref()
}
}
/// Error that can be converted to `HttpResponse`
pub trait ResponseError: Fail {
2017-11-16 07:06:28 +01:00
/// Create response for error
///
/// Internal server error is generated by default.
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Body::Empty)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.cause, f)
}
}
2017-11-20 04:26:31 +01:00
/// `HttpResponse` for `Error`
2017-11-16 07:06:28 +01:00
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
2017-11-25 18:03:44 +01:00
HttpResponse::from_error(err)
2017-11-16 07:06:28 +01:00
}
}
/// `Error` for any error that implements `ResponseError`
impl<T: ResponseError> From<T> for Error {
2017-11-16 07:06:28 +01:00
fn from(err: T) -> Error {
Error { cause: Box::new(err) }
}
}
/// Default error is `InternalServerError`
2017-11-24 19:28:43 +01:00
#[cfg(actix_nightly)]
default impl<T: StdError + Sync + Send + 'static> ResponseError for T {
2017-11-24 19:28:43 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Body::Empty)
}
}
/// `InternalServerError` for `JsonError`
impl ResponseError for JsonError {}
2017-11-16 07:06:28 +01:00
2017-11-25 19:52:43 +01:00
/// Return `InternalServerError` for `HttpError`,
/// Response generation can return `HttpError`, so it is internal error
impl ResponseError for HttpError {}
2017-11-25 19:52:43 +01:00
/// Return `InternalServerError` for `io::Error`
2017-12-02 23:58:22 +01:00
impl ResponseError for io::Error {
fn error_response(&self) -> HttpResponse {
match self.kind() {
io::ErrorKind::NotFound =>
HttpResponse::new(StatusCode::NOT_FOUND, Body::Empty),
io::ErrorKind::PermissionDenied =>
HttpResponse::new(StatusCode::FORBIDDEN, Body::Empty),
_ =>
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Body::Empty)
}
}
}
2017-11-25 19:52:43 +01:00
/// `InternalServerError` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValue {}
2017-11-25 19:52:43 +01:00
2017-12-21 05:30:54 +01:00
/// `InternalServerError` for `futures::Canceled`
impl ResponseError for Canceled {}
2017-11-25 07:15:52 +01:00
/// Internal error
#[derive(Fail, Debug)]
#[fail(display="Unexpected task frame")]
pub struct UnexpectedTaskFrame;
impl ResponseError for UnexpectedTaskFrame {}
2017-11-25 07:15:52 +01:00
2017-11-20 04:26:31 +01:00
/// A set of errors that can occur during parsing HTTP streams
2017-11-16 07:06:28 +01:00
#[derive(Fail, Debug)]
pub enum ParseError {
2017-11-20 04:26:31 +01:00
/// An invalid `Method`, such as `GE.T`.
2017-11-16 07:06:28 +01:00
#[fail(display="Invalid Method specified")]
2017-10-07 06:48:14 +02:00
Method,
/// An invalid `Uri`, such as `exam ple.domain`.
2017-12-01 04:01:25 +01:00
#[fail(display="Uri error: {}", _0)]
Uri(InvalidUriBytes),
2017-10-07 06:48:14 +02:00
/// An invalid `HttpVersion`, such as `HTP/1.1`
2017-11-16 07:06:28 +01:00
#[fail(display="Invalid HTTP version specified")]
2017-10-07 06:48:14 +02:00
Version,
/// An invalid `Header`.
2017-11-16 07:06:28 +01:00
#[fail(display="Invalid Header provided")]
2017-10-07 06:48:14 +02:00
Header,
/// A message head is too large to be reasonable.
2017-11-16 07:06:28 +01:00
#[fail(display="Message head is too large")]
2017-10-07 06:48:14 +02:00
TooLarge,
/// A message reached EOF, but is not complete.
2017-11-16 07:06:28 +01:00
#[fail(display="Message is incomplete")]
2017-10-07 06:48:14 +02:00
Incomplete,
/// An invalid `Status`, such as `1337 ELITE`.
2017-11-16 07:06:28 +01:00
#[fail(display="Invalid Status provided")]
2017-10-07 06:48:14 +02:00
Status,
/// A timeout occurred waiting for an IO event.
#[allow(dead_code)]
2017-11-16 07:06:28 +01:00
#[fail(display="Timeout")]
2017-10-07 06:48:14 +02:00
Timeout,
/// An `io::Error` that occurred while trying to read or write to a network stream.
2017-11-16 07:06:28 +01:00
#[fail(display="IO error: {}", _0)]
2017-11-16 07:28:02 +01:00
Io(#[cause] IoError),
2017-10-07 06:48:14 +02:00
/// Parsing a field as string failed
2017-11-16 07:06:28 +01:00
#[fail(display="UTF8 error: {}", _0)]
2017-11-16 07:28:02 +01:00
Utf8(#[cause] Utf8Error),
2017-10-07 06:48:14 +02:00
}
2017-11-16 07:06:28 +01:00
/// Return `BadRequest` for `ParseError`
impl ResponseError for ParseError {
2017-11-16 07:06:28 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
2017-10-07 06:48:14 +02:00
}
}
impl From<IoError> for ParseError {
fn from(err: IoError) -> ParseError {
ParseError::Io(err)
2017-10-07 06:48:14 +02:00
}
}
impl From<Utf8Error> for ParseError {
fn from(err: Utf8Error) -> ParseError {
ParseError::Utf8(err)
2017-10-07 06:48:14 +02:00
}
}
impl From<FromUtf8Error> for ParseError {
fn from(err: FromUtf8Error) -> ParseError {
ParseError::Utf8(err.utf8_error())
2017-10-07 06:48:14 +02:00
}
}
impl From<httparse::Error> for ParseError {
fn from(err: httparse::Error) -> ParseError {
2017-10-07 06:48:14 +02:00
match err {
2017-12-02 21:14:16 +01:00
httparse::Error::HeaderName | httparse::Error::HeaderValue |
httparse::Error::NewLine | httparse::Error::Token => ParseError::Header,
httparse::Error::Status => ParseError::Status,
httparse::Error::TooManyHeaders => ParseError::TooLarge,
httparse::Error::Version => ParseError::Version,
2017-10-07 06:48:14 +02:00
}
}
}
2017-11-16 07:06:28 +01:00
#[derive(Fail, Debug)]
2017-11-20 04:26:31 +01:00
/// A set of errors that can occur during payload parsing
2017-11-16 07:06:28 +01:00
pub enum PayloadError {
/// A payload reached EOF, but is not complete.
#[fail(display="A payload reached EOF, but is not complete.")]
Incomplete,
/// Content encoding stream corruption
#[fail(display="Can not decode content-encoding.")]
EncodingCorrupted,
/// Parse error
#[fail(display="{}", _0)]
ParseError(#[cause] IoError),
/// Http2 error
#[fail(display="{}", _0)]
Http2(#[cause] Http2Error),
}
impl From<IoError> for PayloadError {
fn from(err: IoError) -> PayloadError {
PayloadError::ParseError(err)
}
}
2017-12-14 07:36:28 +01:00
/// `InternalServerError` for `PayloadError`
impl ResponseError for PayloadError {}
2017-11-16 07:06:28 +01:00
/// Return `BadRequest` for `cookie::ParseError`
impl ResponseError for cookie::ParseError {
2017-11-16 07:06:28 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
}
}
2017-11-16 07:06:28 +01:00
/// Http range header parsing error
2017-11-20 04:58:47 +01:00
#[derive(Fail, PartialEq, Debug)]
2017-11-16 07:06:28 +01:00
pub enum HttpRangeError {
/// Returned if range is invalid.
#[fail(display="Range header is invalid")]
InvalidRange,
/// Returned if first-byte-pos of all of the byte-range-spec
/// values is greater than the content size.
2017-12-06 20:00:39 +01:00
/// See `https://github.com/golang/go/commit/aa9b3d7`
2017-11-16 07:06:28 +01:00
#[fail(display="First-byte-pos of all of the byte-range-spec values is greater than the content size")]
NoOverlap,
}
/// Return `BadRequest` for `HttpRangeError`
impl ResponseError for HttpRangeError {
2017-11-16 07:06:28 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(
StatusCode::BAD_REQUEST, Body::from("Invalid Range header provided"))
2017-10-30 05:39:59 +01:00
}
}
2017-11-16 07:06:28 +01:00
impl From<HttpRangeParseError> for HttpRangeError {
fn from(err: HttpRangeParseError) -> HttpRangeError {
match err {
HttpRangeParseError::InvalidRange => HttpRangeError::InvalidRange,
HttpRangeParseError::NoOverlap => HttpRangeError::NoOverlap,
}
}
}
2017-11-20 04:26:31 +01:00
/// A set of errors that can occur during parsing multipart streams
2017-11-16 07:06:28 +01:00
#[derive(Fail, Debug)]
pub enum MultipartError {
/// Content-Type header is not found
#[fail(display="No Content-type header found")]
NoContentType,
/// Can not parse Content-Type header
#[fail(display="Can not parse Content-Type header")]
ParseContentType,
/// Multipart boundary is not found
#[fail(display="Multipart boundary is not found")]
Boundary,
/// Error during field parsing
#[fail(display="{}", _0)]
Parse(#[cause] ParseError),
/// Payload error
#[fail(display="{}", _0)]
Payload(#[cause] PayloadError),
}
impl From<ParseError> for MultipartError {
fn from(err: ParseError) -> MultipartError {
MultipartError::Parse(err)
}
}
impl From<PayloadError> for MultipartError {
fn from(err: PayloadError) -> MultipartError {
MultipartError::Payload(err)
}
}
2017-10-20 01:22:21 +02:00
/// Return `BadRequest` for `MultipartError`
impl ResponseError for MultipartError {
2017-11-16 07:06:28 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
2017-10-20 01:22:21 +02:00
}
}
2017-11-20 04:51:14 +01:00
/// Error during handling `Expect` header
#[derive(Fail, PartialEq, Debug)]
pub enum ExpectError {
/// Expect header value can not be converted to utf8
#[fail(display="Expect header value can not be converted to utf8")]
Encoding,
/// Unknown expect value
#[fail(display="Unknown expect value")]
UnknownExpect,
}
impl ResponseError for ExpectError {
2017-11-20 04:51:14 +01:00
fn error_response(&self) -> HttpResponse {
HTTPExpectationFailed.with_body("Unknown Expect")
}
}
2017-11-16 07:06:28 +01:00
/// Websocket handshake errors
#[derive(Fail, PartialEq, Debug)]
pub enum WsHandshakeError {
/// Only get method is allowed
#[fail(display="Method not allowed")]
GetMethodRequired,
/// Ugrade header if not set to websocket
#[fail(display="Websocket upgrade is expected")]
NoWebsocketUpgrade,
/// Connection header is not set to upgrade
#[fail(display="Connection upgrade is expected")]
NoConnectionUpgrade,
/// Websocket version header is not set
#[fail(display="Websocket version header is required")]
NoVersionHeader,
/// Unsupported websockt version
#[fail(display="Unsupported version")]
UnsupportedVersion,
/// Websocket key is not set or wrong
#[fail(display="Unknown websocket key")]
BadWebsocketKey,
}
impl ResponseError for WsHandshakeError {
2017-11-16 07:06:28 +01:00
fn error_response(&self) -> HttpResponse {
match *self {
WsHandshakeError::GetMethodRequired => {
HTTPMethodNotAllowed
2017-11-27 07:31:29 +01:00
.build()
2017-11-16 07:06:28 +01:00
.header(header::ALLOW, "GET")
.finish()
.unwrap()
}
WsHandshakeError::NoWebsocketUpgrade =>
HTTPBadRequest.with_reason("No WebSocket UPGRADE header found"),
WsHandshakeError::NoConnectionUpgrade =>
HTTPBadRequest.with_reason("No CONNECTION upgrade"),
WsHandshakeError::NoVersionHeader =>
HTTPBadRequest.with_reason("Websocket version header is required"),
WsHandshakeError::UnsupportedVersion =>
HTTPBadRequest.with_reason("Unsupported version"),
WsHandshakeError::BadWebsocketKey =>
2017-12-13 06:32:58 +01:00
HTTPBadRequest.with_reason("Handshake error"),
2017-11-16 07:06:28 +01:00
}
}
}
2017-11-27 07:00:25 +01:00
/// A set of errors that can occur during parsing urlencoded payloads
2017-12-19 23:03:01 +01:00
#[derive(Fail, Debug)]
2017-11-27 07:00:25 +01:00
pub enum UrlencodedError {
/// Can not decode chunked transfer encoding
#[fail(display="Can not decode chunked transfer encoding")]
Chunked,
/// Payload size is bigger than 256k
#[fail(display="Payload size is bigger than 256k")]
Overflow,
/// Payload size is now known
#[fail(display="Payload size is now known")]
UnknownLength,
/// Content type error
#[fail(display="Content type error")]
ContentType,
2017-12-19 23:03:01 +01:00
/// Payload error
#[fail(display="Error that occur during reading payload")]
Payload(PayloadError),
2017-11-27 07:00:25 +01:00
}
/// Return `BadRequest` for `UrlencodedError`
impl ResponseError for UrlencodedError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
}
}
2017-12-19 23:03:01 +01:00
impl From<PayloadError> for UrlencodedError {
fn from(err: PayloadError) -> UrlencodedError {
UrlencodedError::Payload(err)
}
}
2017-12-21 05:30:54 +01:00
/// A set of errors that can occur during parsing json payloads
#[derive(Fail, Debug)]
pub enum JsonPayloadError {
/// Payload size is bigger than 256k
#[fail(display="Payload size is bigger than 256k")]
Overflow,
/// Content type error
#[fail(display="Content type error")]
ContentType,
/// Deserialize error
#[fail(display="Json deserialize error")]
Deserialize(JsonError),
/// Payload error
#[fail(display="Error that occur during reading payload")]
Payload(PayloadError),
}
/// Return `BadRequest` for `UrlencodedError`
impl ResponseError for JsonPayloadError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
}
}
impl From<PayloadError> for JsonPayloadError {
fn from(err: PayloadError) -> JsonPayloadError {
JsonPayloadError::Payload(err)
}
}
impl From<JsonError> for JsonPayloadError {
fn from(err: JsonError) -> JsonPayloadError {
JsonPayloadError::Deserialize(err)
}
}
/// Errors which can occur when attempting to interpret a segment string as a
/// valid path segment.
#[derive(Fail, Debug, PartialEq)]
pub enum UriSegmentError {
/// The segment started with the wrapped invalid character.
#[fail(display="The segment started with the wrapped invalid character")]
BadStart(char),
/// The segment contained the wrapped invalid character.
#[fail(display="The segment contained the wrapped invalid character")]
BadChar(char),
/// The segment ended with the wrapped invalid character.
#[fail(display="The segment ended with the wrapped invalid character")]
BadEnd(char),
}
/// Return `BadRequest` for `UriSegmentError`
impl ResponseError for UriSegmentError {
2017-11-27 07:00:25 +01:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST, Body::Empty)
}
}
2017-12-05 22:31:06 +01:00
/// Errors which can occur when attempting to generate resource uri.
#[derive(Fail, Debug, PartialEq)]
2017-12-07 01:26:27 +01:00
pub enum UrlGenerationError {
2017-12-05 22:31:06 +01:00
#[fail(display="Resource not found")]
ResourceNotFound,
#[fail(display="Not all path pattern covered")]
NotEnoughElements,
2017-12-07 01:26:27 +01:00
#[fail(display="Router is not available")]
RouterNotAvailable,
#[fail(display="{}", _0)]
ParseError(#[cause] UrlParseError),
}
/// `InternalServerError` for `UrlGeneratorError`
impl ResponseError for UrlGenerationError {}
impl From<UrlParseError> for UrlGenerationError {
fn from(err: UrlParseError) -> Self {
UrlGenerationError::ParseError(err)
}
2017-12-05 22:31:06 +01:00
}
2017-12-09 00:52:46 +01:00
macro_rules! ERROR_WRAP {
($type:ty, $status:expr) => {
unsafe impl<T> Sync for $type {}
unsafe impl<T> Send for $type {}
impl<T> $type {
pub fn cause(&self) -> &T {
&self.0
}
}
impl<T: fmt::Debug + 'static> Fail for $type {}
impl<T: fmt::Debug + 'static> fmt::Display for $type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T> ResponseError for $type
where T: Send + Sync + fmt::Debug + 'static,
{
fn error_response(&self) -> HttpResponse {
HttpResponse::new($status, Body::Empty)
}
}
}
}
2017-12-09 00:25:37 +01:00
/// Helper type that can wrap any error and generate *BAD REQUEST* response.
///
/// In following example any `io::Error` will be converted into "BAD REQUEST" response
/// as oposite to *INNTERNAL SERVER ERROR* which is defined by default.
///
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::*;
/// use actix_web::fs::NamedFile;
///
/// fn index(req: HttpRequest) -> Result<fs::NamedFile> {
/// let f = NamedFile::open("test.txt").map_err(error::ErrorBadRequest)?;
/// Ok(f)
/// }
/// # fn main() {}
/// ```
#[derive(Debug)]
pub struct ErrorBadRequest<T>(pub T);
2017-12-09 00:52:46 +01:00
ERROR_WRAP!(ErrorBadRequest<T>, StatusCode::BAD_REQUEST);
2017-12-09 00:25:37 +01:00
2017-12-09 00:52:46 +01:00
#[derive(Debug)]
/// Helper type that can wrap any error and generate *UNAUTHORIZED* response.
pub struct ErrorUnauthorized<T>(pub T);
ERROR_WRAP!(ErrorUnauthorized<T>, StatusCode::UNAUTHORIZED);
2017-12-09 00:25:37 +01:00
2017-12-09 00:52:46 +01:00
#[derive(Debug)]
/// Helper type that can wrap any error and generate *FORBIDDEN* response.
pub struct ErrorForbidden<T>(pub T);
ERROR_WRAP!(ErrorForbidden<T>, StatusCode::FORBIDDEN);
2017-12-09 00:25:37 +01:00
2017-12-09 00:52:46 +01:00
#[derive(Debug)]
/// Helper type that can wrap any error and generate *NOT FOUND* response.
pub struct ErrorNotFound<T>(pub T);
ERROR_WRAP!(ErrorNotFound<T>, StatusCode::NOT_FOUND);
2017-12-09 00:25:37 +01:00
2017-12-09 00:52:46 +01:00
#[derive(Debug)]
2017-12-09 13:33:40 +01:00
/// Helper type that can wrap any error and generate *METHOD NOT ALLOWED* response.
2017-12-09 00:52:46 +01:00
pub struct ErrorMethodNotAllowed<T>(pub T);
ERROR_WRAP!(ErrorMethodNotAllowed<T>, StatusCode::METHOD_NOT_ALLOWED);
#[derive(Debug)]
2017-12-09 13:33:40 +01:00
/// Helper type that can wrap any error and generate *REQUEST TIMEOUT* response.
2017-12-09 00:52:46 +01:00
pub struct ErrorRequestTimeout<T>(pub T);
ERROR_WRAP!(ErrorRequestTimeout<T>, StatusCode::REQUEST_TIMEOUT);
#[derive(Debug)]
/// Helper type that can wrap any error and generate *CONFLICT* response.
pub struct ErrorConflict<T>(pub T);
ERROR_WRAP!(ErrorConflict<T>, StatusCode::CONFLICT);
#[derive(Debug)]
/// Helper type that can wrap any error and generate *GONE* response.
pub struct ErrorGone<T>(pub T);
ERROR_WRAP!(ErrorGone<T>, StatusCode::GONE);
#[derive(Debug)]
2017-12-09 13:33:40 +01:00
/// Helper type that can wrap any error and generate *PRECONDITION FAILED* response.
2017-12-09 00:52:46 +01:00
pub struct ErrorPreconditionFailed<T>(pub T);
ERROR_WRAP!(ErrorPreconditionFailed<T>, StatusCode::PRECONDITION_FAILED);
#[derive(Debug)]
2017-12-09 13:33:40 +01:00
/// Helper type that can wrap any error and generate *EXPECTATION FAILED* response.
2017-12-09 00:52:46 +01:00
pub struct ErrorExpectationFailed<T>(pub T);
ERROR_WRAP!(ErrorExpectationFailed<T>, StatusCode::EXPECTATION_FAILED);
#[derive(Debug)]
2017-12-09 13:33:40 +01:00
/// Helper type that can wrap any error and generate *INTERNAL SERVER ERROR* response.
2017-12-09 00:52:46 +01:00
pub struct ErrorInternalServerError<T>(pub T);
ERROR_WRAP!(ErrorInternalServerError<T>, StatusCode::INTERNAL_SERVER_ERROR);
2017-12-09 00:25:37 +01:00
2017-10-07 06:48:14 +02:00
#[cfg(test)]
mod tests {
use std::error::Error as StdError;
use std::io;
use httparse;
2017-10-22 18:45:53 +02:00
use http::{StatusCode, Error as HttpError};
2017-10-15 08:14:26 +02:00
use cookie::ParseError as CookieParseError;
2017-11-16 07:06:28 +01:00
use super::*;
2017-10-15 08:14:26 +02:00
2017-11-24 19:28:43 +01:00
#[test]
#[cfg(actix_nightly)]
fn test_nightly() {
let resp: HttpResponse = IoError::new(io::ErrorKind::Other, "test").error_response();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
2017-10-15 08:14:26 +02:00
#[test]
fn test_into_response() {
2017-11-16 07:06:28 +01:00
let resp: HttpResponse = ParseError::Incomplete.error_response();
2017-10-15 08:14:26 +02:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-11-16 07:06:28 +01:00
let resp: HttpResponse = HttpRangeError::InvalidRange.error_response();
2017-10-15 08:14:26 +02:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-11-16 07:06:28 +01:00
let resp: HttpResponse = CookieParseError::EmptyName.error_response();
2017-10-15 08:14:26 +02:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-10-22 18:45:53 +02:00
2017-11-16 07:06:28 +01:00
let resp: HttpResponse = MultipartError::Boundary.error_response();
2017-10-22 18:45:53 +02:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
2017-11-16 07:06:28 +01:00
let resp: HttpResponse = err.error_response();
2017-10-22 18:45:53 +02:00
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
2017-10-07 06:48:14 +02:00
#[test]
fn test_cause() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
2017-10-14 01:33:23 +02:00
let e = ParseError::Io(orig);
2017-11-16 07:06:28 +01:00
assert_eq!(format!("{}", e.cause().unwrap()), desc);
2017-10-07 06:48:14 +02:00
}
2017-11-20 04:26:31 +01:00
#[test]
fn test_error_cause() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
let e = Error::from(orig);
assert_eq!(format!("{}", e.cause()), desc);
}
2017-11-20 04:58:47 +01:00
#[test]
fn test_error_display() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
let e = Error::from(orig);
assert_eq!(format!("{}", e), desc);
}
#[test]
fn test_error_http_response() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let e = Error::from(orig);
let resp: HttpResponse = e.into();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_range_error() {
let e: HttpRangeError = HttpRangeParseError::InvalidRange.into();
assert_eq!(e, HttpRangeError::InvalidRange);
let e: HttpRangeError = HttpRangeParseError::NoOverlap.into();
assert_eq!(e, HttpRangeError::NoOverlap);
}
2017-11-20 05:02:31 +01:00
#[test]
fn test_expect_error() {
let resp: HttpResponse = ExpectError::Encoding.error_response();
assert_eq!(resp.status(), StatusCode::EXPECTATION_FAILED);
let resp: HttpResponse = ExpectError::UnknownExpect.error_response();
assert_eq!(resp.status(), StatusCode::EXPECTATION_FAILED);
}
2017-11-20 04:58:47 +01:00
#[test]
fn test_wserror_http_response() {
let resp: HttpResponse = WsHandshakeError::GetMethodRequired.error_response();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let resp: HttpResponse = WsHandshakeError::NoWebsocketUpgrade.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = WsHandshakeError::NoConnectionUpgrade.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = WsHandshakeError::NoVersionHeader.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = WsHandshakeError::UnsupportedVersion.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: HttpResponse = WsHandshakeError::BadWebsocketKey.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
2017-10-07 06:48:14 +02:00
macro_rules! from {
($from:expr => $error:pat) => {
2017-10-14 01:33:23 +02:00
match ParseError::from($from) {
2017-10-07 06:48:14 +02:00
e @ $error => {
2017-11-16 07:06:28 +01:00
assert!(format!("{}", e).len() >= 5);
2017-10-07 06:48:14 +02:00
} ,
e => panic!("{:?}", e)
}
}
}
macro_rules! from_and_cause {
($from:expr => $error:pat) => {
2017-10-14 01:33:23 +02:00
match ParseError::from($from) {
2017-10-07 06:48:14 +02:00
e @ $error => {
2017-11-16 07:06:28 +01:00
let desc = format!("{}", e.cause().unwrap());
2017-10-07 06:48:14 +02:00
assert_eq!(desc, $from.description().to_owned());
},
_ => panic!("{:?}", $from)
}
}
}
#[test]
fn test_from() {
2017-10-14 01:33:23 +02:00
from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => ParseError::Io(..));
from!(httparse::Error::HeaderName => ParseError::Header);
from!(httparse::Error::HeaderName => ParseError::Header);
from!(httparse::Error::HeaderValue => ParseError::Header);
from!(httparse::Error::NewLine => ParseError::Header);
from!(httparse::Error::Status => ParseError::Status);
from!(httparse::Error::Token => ParseError::Header);
from!(httparse::Error::TooManyHeaders => ParseError::TooLarge);
from!(httparse::Error::Version => ParseError::Version);
2017-10-07 06:48:14 +02:00
}
}