1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-10 20:22:07 +00:00
actix-web/src/error.rs

896 lines
26 KiB
Rust
Raw Normal View History

2017-11-20 03:26:31 +00:00
//! Error and Result module
use std::cell::RefCell;
2018-04-13 23:02:01 +00:00
use std::io::Error as IoError;
2017-10-07 04:48:14 +00:00
use std::str::Utf8Error;
use std::string::FromUtf8Error;
2018-04-13 23:02:01 +00:00
use std::{fmt, io, result};
2017-10-07 04:48:14 +00:00
use actix::MailboxError;
2018-04-13 23:02:01 +00:00
use cookie;
use failure::{self, Backtrace, Fail};
2017-12-21 04:30:54 +00:00
use futures::Canceled;
use http::uri::InvalidUri;
2018-04-13 23:02:01 +00:00
use http::{header, Error as HttpError, StatusCode};
use http2::Error as Http2Error;
2017-11-16 06:06:28 +00:00
use http_range::HttpRangeParseError;
2018-04-13 23:02:01 +00:00
use httparse;
2018-03-27 01:18:38 +00:00
use serde::de::value::Error as DeError;
use serde_json::error::Error as JsonError;
2018-01-28 06:03:03 +00:00
pub use url::ParseError as UrlParseError;
2017-11-16 06:06:28 +00:00
// re-exports
2018-04-13 23:02:01 +00:00
pub use cookie::ParseError as CookieParseError;
2017-10-07 04:48:14 +00:00
2018-01-21 04:12:24 +00:00
use handler::Responder;
use httprequest::HttpRequest;
2017-11-16 06:06:28 +00:00
use httpresponse::HttpResponse;
2017-10-07 04:48:14 +00:00
2017-11-16 06:06:28 +00:00
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
2017-11-20 03:26:31 +00:00
/// for actix web operations
2017-11-16 06:06:28 +00:00
///
2018-04-13 23:02:01 +00:00
/// This typedef is generally used to avoid writing out
/// `actix_web::error::Error` directly and is otherwise a direct mapping to
/// `Result`.
pub type Result<T, E = Error> = result::Result<T, E>;
2017-11-27 01:30:35 +00:00
/// General purpose actix web error
2017-11-16 06:06:28 +00:00
pub struct Error {
cause: Box<ResponseError>,
2018-01-21 04:12:24 +00:00
backtrace: Option<Backtrace>,
2017-11-16 06:06:28 +00:00
}
2017-11-20 03:26:31 +00: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 03:26:31 +00:00
self.cause.as_ref()
}
}
/// Error that can be converted to `HttpResponse`
pub trait ResponseError: Fail {
2017-11-16 06:06:28 +00:00
/// Create response for error
///
/// Internal server error is generated by default.
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
2017-11-16 06:06:28 +00:00
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.cause, f)
}
}
2018-01-21 04:12:24 +00:00
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2018-01-21 05:11:46 +00:00
if let Some(bt) = self.cause.backtrace() {
write!(f, "{:?}\n\n{:?}", &self.cause, bt)
2018-01-21 04:12:24 +00:00
} else {
2018-04-13 23:02:01 +00:00
write!(
f,
"{:?}\n\n{:?}",
&self.cause,
self.backtrace.as_ref().unwrap()
)
2018-01-21 04:12:24 +00:00
}
}
}
2017-11-20 03:26:31 +00:00
/// `HttpResponse` for `Error`
2017-11-16 06:06:28 +00:00
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
2017-11-25 17:03:44 +00:00
HttpResponse::from_error(err)
2017-11-16 06:06:28 +00:00
}
}
/// `Error` for any error that implements `ResponseError`
impl<T: ResponseError> From<T> for Error {
2017-11-16 06:06:28 +00:00
fn from(err: T) -> Error {
2018-01-21 04:12:24 +00:00
let backtrace = if err.backtrace().is_none() {
Some(Backtrace::new())
} else {
None
};
2018-04-13 23:02:01 +00:00
Error {
cause: Box::new(err),
backtrace,
}
2017-11-16 06:06:28 +00:00
}
}
/// Compatibility for `failure::Error`
impl<T> ResponseError for failure::Compat<T>
2018-04-13 23:02:01 +00:00
where
T: fmt::Display + fmt::Debug + Sync + Send + 'static,
{
}
impl From<failure::Error> for Error {
fn from(err: failure::Error) -> Error {
err.compat().into()
}
}
/// `InternalServerError` for `JsonError`
impl ResponseError for JsonError {}
2017-11-16 06:06:28 +00:00
2018-01-28 06:03:03 +00:00
/// `InternalServerError` for `UrlParseError`
impl ResponseError for UrlParseError {}
2018-03-27 01:18:38 +00:00
/// Return `BAD_REQUEST` for `de::value::Error`
impl ResponseError for DeError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
2018-03-27 01:18:38 +00:00
}
}
2018-04-02 23:19:18 +00:00
/// Return `BAD_REQUEST` for `Utf8Error`
impl ResponseError for Utf8Error {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
2017-11-25 18:52:43 +00:00
/// Return `InternalServerError` for `HttpError`,
/// Response generation can return `HttpError`, so it is internal error
impl ResponseError for HttpError {}
2017-11-25 18:52:43 +00:00
/// Return `InternalServerError` for `io::Error`
2017-12-02 22:58:22 +00:00
impl ResponseError for io::Error {
fn error_response(&self) -> HttpResponse {
match self.kind() {
2018-04-13 23:02:01 +00:00
io::ErrorKind::NotFound => HttpResponse::new(StatusCode::NOT_FOUND),
io::ErrorKind::PermissionDenied => HttpResponse::new(StatusCode::FORBIDDEN),
_ => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR),
2017-12-02 22:58:22 +00:00
}
}
}
2017-11-25 18:52:43 +00:00
/// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValue {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
2018-04-13 23:02:01 +00:00
}
}
/// `BadRequest` for `InvalidHeaderValue`
impl ResponseError for header::InvalidHeaderValueBytes {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
2017-11-25 18:52:43 +00:00
2017-12-21 04:30:54 +00:00
/// `InternalServerError` for `futures::Canceled`
impl ResponseError for Canceled {}
/// `InternalServerError` for `actix::MailboxError`
impl ResponseError for MailboxError {}
2017-11-20 03:26:31 +00:00
/// A set of errors that can occur during parsing HTTP streams
2017-11-16 06:06:28 +00:00
#[derive(Fail, Debug)]
pub enum ParseError {
2017-11-20 03:26:31 +00:00
/// An invalid `Method`, such as `GE.T`.
2018-04-13 23:02:01 +00:00
#[fail(display = "Invalid Method specified")]
2017-10-07 04:48:14 +00:00
Method,
/// An invalid `Uri`, such as `exam ple.domain`.
2018-04-13 23:02:01 +00:00
#[fail(display = "Uri error: {}", _0)]
Uri(InvalidUri),
2017-10-07 04:48:14 +00:00
/// An invalid `HttpVersion`, such as `HTP/1.1`
2018-04-13 23:02:01 +00:00
#[fail(display = "Invalid HTTP version specified")]
2017-10-07 04:48:14 +00:00
Version,
/// An invalid `Header`.
2018-04-13 23:02:01 +00:00
#[fail(display = "Invalid Header provided")]
2017-10-07 04:48:14 +00:00
Header,
/// A message head is too large to be reasonable.
2018-04-13 23:02:01 +00:00
#[fail(display = "Message head is too large")]
2017-10-07 04:48:14 +00:00
TooLarge,
/// A message reached EOF, but is not complete.
2018-04-13 23:02:01 +00:00
#[fail(display = "Message is incomplete")]
2017-10-07 04:48:14 +00:00
Incomplete,
/// An invalid `Status`, such as `1337 ELITE`.
2018-04-13 23:02:01 +00:00
#[fail(display = "Invalid Status provided")]
2017-10-07 04:48:14 +00:00
Status,
/// A timeout occurred waiting for an IO event.
#[allow(dead_code)]
2018-04-13 23:02:01 +00:00
#[fail(display = "Timeout")]
2017-10-07 04:48:14 +00:00
Timeout,
2018-04-13 23:02:01 +00:00
/// An `io::Error` that occurred while trying to read or write to a network
/// stream.
#[fail(display = "IO error: {}", _0)]
2017-11-16 06:28:02 +00:00
Io(#[cause] IoError),
2017-10-07 04:48:14 +00:00
/// Parsing a field as string failed
2018-04-13 23:02:01 +00:00
#[fail(display = "UTF8 error: {}", _0)]
2017-11-16 06:28:02 +00:00
Utf8(#[cause] Utf8Error),
2017-10-07 04:48:14 +00:00
}
2017-11-16 06:06:28 +00:00
/// Return `BadRequest` for `ParseError`
impl ResponseError for ParseError {
2017-11-16 06:06:28 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
2017-10-07 04:48:14 +00:00
}
}
impl From<IoError> for ParseError {
fn from(err: IoError) -> ParseError {
ParseError::Io(err)
2017-10-07 04:48:14 +00:00
}
}
impl From<InvalidUri> for ParseError {
fn from(err: InvalidUri) -> ParseError {
ParseError::Uri(err)
}
}
impl From<Utf8Error> for ParseError {
fn from(err: Utf8Error) -> ParseError {
ParseError::Utf8(err)
2017-10-07 04:48:14 +00:00
}
}
impl From<FromUtf8Error> for ParseError {
fn from(err: FromUtf8Error) -> ParseError {
ParseError::Utf8(err.utf8_error())
2017-10-07 04:48:14 +00:00
}
}
impl From<httparse::Error> for ParseError {
fn from(err: httparse::Error) -> ParseError {
2017-10-07 04:48:14 +00:00
match err {
2018-04-13 23:02:01 +00: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 04:48:14 +00:00
}
}
}
2017-11-16 06:06:28 +00:00
#[derive(Fail, Debug)]
2017-11-20 03:26:31 +00:00
/// A set of errors that can occur during payload parsing
2017-11-16 06:06:28 +00:00
pub enum PayloadError {
/// A payload reached EOF, but is not complete.
2018-04-13 23:02:01 +00:00
#[fail(display = "A payload reached EOF, but is not complete.")]
2017-11-16 06:06:28 +00:00
Incomplete,
/// Content encoding stream corruption
2018-04-13 23:02:01 +00:00
#[fail(display = "Can not decode content-encoding.")]
2017-11-16 06:06:28 +00:00
EncodingCorrupted,
/// A payload reached size limit.
2018-04-13 23:02:01 +00:00
#[fail(display = "A payload reached size limit.")]
Overflow,
/// A payload length is unknown.
2018-04-13 23:02:01 +00:00
#[fail(display = "A payload length is unknown.")]
UnknownLength,
2018-02-20 06:48:27 +00:00
/// Io error
2018-04-13 23:02:01 +00:00
#[fail(display = "{}", _0)]
2018-02-20 06:48:27 +00:00
Io(#[cause] IoError),
2017-11-16 06:06:28 +00:00
/// Http2 error
2018-04-13 23:02:01 +00:00
#[fail(display = "{}", _0)]
2017-11-16 06:06:28 +00:00
Http2(#[cause] Http2Error),
}
impl From<IoError> for PayloadError {
fn from(err: IoError) -> PayloadError {
2018-02-20 06:48:27 +00:00
PayloadError::Io(err)
}
}
2017-12-14 06:36:28 +00:00
/// `InternalServerError` for `PayloadError`
impl ResponseError for PayloadError {}
2017-11-16 06:06:28 +00:00
/// Return `BadRequest` for `cookie::ParseError`
impl ResponseError for cookie::ParseError {
2017-11-16 06:06:28 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
2017-11-16 06:06:28 +00:00
/// Http range header parsing error
2017-11-20 03:58:47 +00:00
#[derive(Fail, PartialEq, Debug)]
2017-11-16 06:06:28 +00:00
pub enum HttpRangeError {
/// Returned if range is invalid.
2018-04-13 23:02:01 +00:00
#[fail(display = "Range header is invalid")]
2017-11-16 06:06:28 +00:00
InvalidRange,
/// Returned if first-byte-pos of all of the byte-range-spec
/// values is greater than the content size.
2017-12-06 19:00:39 +00:00
/// See `https://github.com/golang/go/commit/aa9b3d7`
2018-04-13 23:02:01 +00:00
#[fail(display = "First-byte-pos of all of the byte-range-spec values is greater than the content size")]
2017-11-16 06:06:28 +00:00
NoOverlap,
}
/// Return `BadRequest` for `HttpRangeError`
impl ResponseError for HttpRangeError {
2017-11-16 06:06:28 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::with_body(
2018-04-13 23:02:01 +00:00
StatusCode::BAD_REQUEST,
"Invalid Range header provided",
)
2017-10-30 04:39:59 +00:00
}
}
2017-11-16 06:06:28 +00:00
impl From<HttpRangeParseError> for HttpRangeError {
fn from(err: HttpRangeParseError) -> HttpRangeError {
match err {
HttpRangeParseError::InvalidRange => HttpRangeError::InvalidRange,
HttpRangeParseError::NoOverlap => HttpRangeError::NoOverlap,
}
}
}
2017-11-20 03:26:31 +00:00
/// A set of errors that can occur during parsing multipart streams
2017-11-16 06:06:28 +00:00
#[derive(Fail, Debug)]
pub enum MultipartError {
/// Content-Type header is not found
2018-04-13 23:02:01 +00:00
#[fail(display = "No Content-type header found")]
2017-11-16 06:06:28 +00:00
NoContentType,
/// Can not parse Content-Type header
2018-04-13 23:02:01 +00:00
#[fail(display = "Can not parse Content-Type header")]
2017-11-16 06:06:28 +00:00
ParseContentType,
/// Multipart boundary is not found
2018-04-13 23:02:01 +00:00
#[fail(display = "Multipart boundary is not found")]
2017-11-16 06:06:28 +00:00
Boundary,
2018-02-26 02:55:07 +00:00
/// Multipart stream is incomplete
2018-04-13 23:02:01 +00:00
#[fail(display = "Multipart stream is incomplete")]
2018-02-26 02:55:07 +00:00
Incomplete,
2017-11-16 06:06:28 +00:00
/// Error during field parsing
2018-04-13 23:02:01 +00:00
#[fail(display = "{}", _0)]
2017-11-16 06:06:28 +00:00
Parse(#[cause] ParseError),
/// Payload error
2018-04-13 23:02:01 +00:00
#[fail(display = "{}", _0)]
2017-11-16 06:06:28 +00:00
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-19 23:22:21 +00:00
/// Return `BadRequest` for `MultipartError`
impl ResponseError for MultipartError {
2017-11-16 06:06:28 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
2017-10-19 23:22:21 +00:00
}
}
2017-11-20 03:51:14 +00:00
/// Error during handling `Expect` header
#[derive(Fail, PartialEq, Debug)]
pub enum ExpectError {
/// Expect header value can not be converted to utf8
2018-04-13 23:02:01 +00:00
#[fail(display = "Expect header value can not be converted to utf8")]
2017-11-20 03:51:14 +00:00
Encoding,
/// Unknown expect value
2018-04-13 23:02:01 +00:00
#[fail(display = "Unknown expect value")]
2017-11-20 03:51:14 +00:00
UnknownExpect,
}
impl ResponseError for ExpectError {
2017-11-20 03:51:14 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::with_body(StatusCode::EXPECTATION_FAILED, "Unknown Expect")
2017-11-20 03:51:14 +00:00
}
}
/// A set of error that can occure during parsing content type
#[derive(Fail, PartialEq, Debug)]
pub enum ContentTypeError {
/// Can not parse content type
2018-04-13 23:02:01 +00:00
#[fail(display = "Can not parse content type")]
ParseError,
/// Unknown content encoding
2018-04-13 23:02:01 +00:00
#[fail(display = "Unknown content encoding")]
UnknownEncoding,
}
/// Return `BadRequest` for `ContentTypeError`
impl ResponseError for ContentTypeError {
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
}
}
2017-11-27 06:00:25 +00:00
/// A set of errors that can occur during parsing urlencoded payloads
2017-12-19 22:03:01 +00:00
#[derive(Fail, Debug)]
2017-11-27 06:00:25 +00:00
pub enum UrlencodedError {
/// Can not decode chunked transfer encoding
2018-04-13 23:02:01 +00:00
#[fail(display = "Can not decode chunked transfer encoding")]
2017-11-27 06:00:25 +00:00
Chunked,
/// Payload size is bigger than 256k
2018-04-13 23:02:01 +00:00
#[fail(display = "Payload size is bigger than 256k")]
2017-11-27 06:00:25 +00:00
Overflow,
/// Payload size is now known
2018-04-13 23:02:01 +00:00
#[fail(display = "Payload size is now known")]
2017-11-27 06:00:25 +00:00
UnknownLength,
/// Content type error
2018-04-13 23:02:01 +00:00
#[fail(display = "Content type error")]
2017-11-27 06:00:25 +00:00
ContentType,
/// Parse error
2018-04-13 23:02:01 +00:00
#[fail(display = "Parse error")]
Parse,
2017-12-19 22:03:01 +00:00
/// Payload error
2018-04-13 23:02:01 +00:00
#[fail(display = "Error that occur during reading payload: {}", _0)]
Payload(#[cause] PayloadError),
2017-11-27 06:00:25 +00:00
}
/// Return `BadRequest` for `UrlencodedError`
impl ResponseError for UrlencodedError {
fn error_response(&self) -> HttpResponse {
2018-01-31 20:34:58 +00:00
match *self {
2018-04-13 23:02:01 +00:00
UrlencodedError::Overflow => {
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE)
}
UrlencodedError::UnknownLength => {
HttpResponse::new(StatusCode::LENGTH_REQUIRED)
}
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
2018-01-31 20:34:58 +00:00
}
}
}
2017-12-19 22:03:01 +00:00
impl From<PayloadError> for UrlencodedError {
fn from(err: PayloadError) -> UrlencodedError {
UrlencodedError::Payload(err)
}
}
2017-12-21 04:30:54 +00:00
/// A set of errors that can occur during parsing json payloads
#[derive(Fail, Debug)]
pub enum JsonPayloadError {
/// Payload size is bigger than 256k
2018-04-13 23:02:01 +00:00
#[fail(display = "Payload size is bigger than 256k")]
2017-12-21 04:30:54 +00:00
Overflow,
/// Content type error
2018-04-13 23:02:01 +00:00
#[fail(display = "Content type error")]
2017-12-21 04:30:54 +00:00
ContentType,
/// Deserialize error
2018-04-13 23:02:01 +00:00
#[fail(display = "Json deserialize error: {}", _0)]
Deserialize(#[cause] JsonError),
2017-12-21 04:30:54 +00:00
/// Payload error
2018-04-13 23:02:01 +00:00
#[fail(display = "Error that occur during reading payload: {}", _0)]
Payload(#[cause] PayloadError),
2017-12-21 04:30:54 +00:00
}
/// Return `BadRequest` for `UrlencodedError`
impl ResponseError for JsonPayloadError {
fn error_response(&self) -> HttpResponse {
2018-01-31 20:34:58 +00:00
match *self {
2018-04-13 23:02:01 +00:00
JsonPayloadError::Overflow => {
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE)
}
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
2018-01-31 20:34:58 +00:00
}
2017-12-21 04:30:54 +00:00
}
}
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.
2018-04-13 23:02:01 +00:00
#[fail(display = "The segment started with the wrapped invalid character")]
BadStart(char),
/// The segment contained the wrapped invalid character.
2018-04-13 23:02:01 +00:00
#[fail(display = "The segment contained the wrapped invalid character")]
BadChar(char),
/// The segment ended with the wrapped invalid character.
2018-04-13 23:02:01 +00:00
#[fail(display = "The segment ended with the wrapped invalid character")]
BadEnd(char),
}
/// Return `BadRequest` for `UriSegmentError`
impl ResponseError for UriSegmentError {
2017-11-27 06:00:25 +00:00
fn error_response(&self) -> HttpResponse {
HttpResponse::new(StatusCode::BAD_REQUEST)
2017-11-27 06:00:25 +00:00
}
}
2017-12-05 21:31:06 +00:00
/// Errors which can occur when attempting to generate resource uri.
#[derive(Fail, Debug, PartialEq)]
2017-12-07 00:26:27 +00:00
pub enum UrlGenerationError {
2018-04-13 23:02:01 +00:00
#[fail(display = "Resource not found")]
2017-12-05 21:31:06 +00:00
ResourceNotFound,
2018-04-13 23:02:01 +00:00
#[fail(display = "Not all path pattern covered")]
2017-12-05 21:31:06 +00:00
NotEnoughElements,
2018-04-13 23:02:01 +00:00
#[fail(display = "Router is not available")]
2017-12-07 00:26:27 +00:00
RouterNotAvailable,
2018-04-13 23:02:01 +00:00
#[fail(display = "{}", _0)]
2017-12-07 00:26:27 +00:00
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 21:31:06 +00:00
}
2018-01-21 05:11:46 +00:00
/// Helper type that can wrap any error and generate custom response.
2017-12-08 23:25:37 +00:00
///
2018-04-13 23:02:01 +00:00
/// In following example any `io::Error` will be converted into "BAD REQUEST"
/// response as opposite to *INNTERNAL SERVER ERROR* which is defined by
/// default.
2017-12-08 23:25:37 +00:00
///
/// ```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() {}
/// ```
2018-01-21 05:11:46 +00:00
pub struct InternalError<T> {
cause: T,
status: InternalErrorType,
2018-01-21 05:11:46 +00:00
backtrace: Backtrace,
}
unsafe impl<T> Sync for InternalError<T> {}
unsafe impl<T> Send for InternalError<T> {}
enum InternalErrorType {
Status(StatusCode),
Response(RefCell<Option<HttpResponse>>),
}
2018-01-21 05:11:46 +00:00
impl<T> InternalError<T> {
2018-04-14 02:14:14 +00:00
/// Create `InternalError` instance
2018-02-26 22:33:56 +00:00
pub fn new(cause: T, status: StatusCode) -> Self {
2018-01-21 05:11:46 +00:00
InternalError {
2018-02-26 22:33:56 +00:00
cause,
status: InternalErrorType::Status(status),
backtrace: Backtrace::new(),
}
}
2018-04-14 02:14:14 +00:00
/// Create `InternalError` with predefined `HttpResponse`
pub fn from_response(cause: T, response: HttpResponse) -> Self {
InternalError {
cause,
status: InternalErrorType::Response(RefCell::new(Some(response))),
2018-01-21 05:11:46 +00:00
backtrace: Backtrace::new(),
}
}
}
impl<T> Fail for InternalError<T>
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
2018-01-21 05:11:46 +00:00
{
fn backtrace(&self) -> Option<&Backtrace> {
Some(&self.backtrace)
}
}
impl<T> fmt::Debug for InternalError<T>
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
2018-01-21 05:11:46 +00:00
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.cause, f)
}
}
impl<T> fmt::Display for InternalError<T>
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
2018-01-21 05:11:46 +00:00
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2018-01-21 06:02:42 +00:00
fmt::Debug::fmt(&self.cause, f)
2018-01-21 05:11:46 +00:00
}
}
impl<T> ResponseError for InternalError<T>
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
2018-01-21 05:11:46 +00:00
{
fn error_response(&self) -> HttpResponse {
match self.status {
InternalErrorType::Status(st) => HttpResponse::new(st),
InternalErrorType::Response(ref resp) => {
if let Some(resp) = resp.borrow_mut().take() {
resp
} else {
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
2018-01-21 05:11:46 +00:00
}
}
impl<T> Responder for InternalError<T>
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
2018-01-21 05:11:46 +00:00
{
type Item = HttpResponse;
type Error = Error;
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
Err(self.into())
}
}
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *BAD
/// REQUEST* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorBadRequest<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::BAD_REQUEST).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:25:37 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate
/// *UNAUTHORIZED* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorUnauthorized<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::UNAUTHORIZED).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:25:37 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *FORBIDDEN*
/// response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorForbidden<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::FORBIDDEN).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:25:37 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *NOT FOUND*
/// response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorNotFound<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::NOT_FOUND).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:25:37 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *METHOD NOT
/// ALLOWED* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorMethodNotAllowed<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::METHOD_NOT_ALLOWED).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *REQUEST
/// TIMEOUT* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorRequestTimeout<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::REQUEST_TIMEOUT).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *CONFLICT*
/// response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorConflict<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::CONFLICT).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate *GONE*
/// response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorGone<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::GONE).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate
/// *PRECONDITION FAILED* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorPreconditionFailed<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::PRECONDITION_FAILED).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
2018-04-13 23:02:01 +00:00
/// Helper function that creates wrapper of any error and generate
/// *EXPECTATION FAILED* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorExpectationFailed<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::EXPECTATION_FAILED).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:52:46 +00:00
/// Helper function that creates wrapper of any error and
/// generate *INTERNAL SERVER ERROR* response.
2018-01-21 05:11:46 +00:00
#[allow(non_snake_case)]
pub fn ErrorInternalServerError<T>(err: T) -> Error
2018-04-13 23:02:01 +00:00
where
T: Send + Sync + fmt::Debug + 'static,
{
InternalError::new(err, StatusCode::INTERNAL_SERVER_ERROR).into()
2018-01-21 05:11:46 +00:00
}
2017-12-08 23:25:37 +00:00
2017-10-07 04:48:14 +00:00
#[cfg(test)]
mod tests {
2018-04-13 23:02:01 +00:00
use super::*;
use cookie::ParseError as CookieParseError;
use failure;
use http::{Error as HttpError, StatusCode};
use httparse;
use std::env;
2017-10-07 04:48:14 +00:00
use std::error::Error as StdError;
use std::io;
2017-10-15 06:14:26 +00:00
2017-11-24 18:28:43 +00:00
#[test]
#[cfg(actix_nightly)]
fn test_nightly() {
2018-04-13 23:02:01 +00:00
let resp: HttpResponse =
IoError::new(io::ErrorKind::Other, "test").error_response();
2017-11-24 18:28:43 +00:00
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
2017-10-15 06:14:26 +00:00
#[test]
fn test_into_response() {
2017-11-16 06:06:28 +00:00
let resp: HttpResponse = ParseError::Incomplete.error_response();
2017-10-15 06:14:26 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-11-16 06:06:28 +00:00
let resp: HttpResponse = HttpRangeError::InvalidRange.error_response();
2017-10-15 06:14:26 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-11-16 06:06:28 +00:00
let resp: HttpResponse = CookieParseError::EmptyName.error_response();
2017-10-15 06:14:26 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2017-10-22 16:45:53 +00:00
2017-11-16 06:06:28 +00:00
let resp: HttpResponse = MultipartError::Boundary.error_response();
2017-10-22 16:45:53 +00:00
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
2017-11-16 06:06:28 +00:00
let resp: HttpResponse = err.error_response();
2017-10-22 16:45:53 +00:00
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
2017-10-07 04:48:14 +00:00
#[test]
fn test_cause() {
let orig = io::Error::new(io::ErrorKind::Other, "other");
let desc = orig.description().to_owned();
2017-10-13 23:33:23 +00:00
let e = ParseError::Io(orig);
2017-11-16 06:06:28 +00:00
assert_eq!(format!("{}", e.cause().unwrap()), desc);
2017-10-07 04:48:14 +00:00
}
2017-11-20 03:26:31 +00: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 03:58:47 +00: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 04:02:31 +00: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-10-07 04:48:14 +00:00
macro_rules! from {
($from:expr => $error:pat) => {
2017-10-13 23:33:23 +00:00
match ParseError::from($from) {
2017-10-07 04:48:14 +00:00
e @ $error => {
2017-11-16 06:06:28 +00:00
assert!(format!("{}", e).len() >= 5);
2018-04-13 23:02:01 +00:00
}
e => unreachable!("{:?}", e),
2017-10-07 04:48:14 +00:00
}
2018-04-13 23:02:01 +00:00
};
2017-10-07 04:48:14 +00:00
}
macro_rules! from_and_cause {
($from:expr => $error:pat) => {
2017-10-13 23:33:23 +00:00
match ParseError::from($from) {
2017-10-07 04:48:14 +00:00
e @ $error => {
2017-11-16 06:06:28 +00:00
let desc = format!("{}", e.cause().unwrap());
2017-10-07 04:48:14 +00:00
assert_eq!(desc, $from.description().to_owned());
2018-04-13 23:02:01 +00:00
}
_ => unreachable!("{:?}", $from),
2017-10-07 04:48:14 +00:00
}
2018-04-13 23:02:01 +00:00
};
2017-10-07 04:48:14 +00:00
}
#[test]
fn test_from() {
2017-10-13 23:33:23 +00: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 04:48:14 +00:00
}
#[test]
fn failure_error() {
const NAME: &str = "RUST_BACKTRACE";
let old_tb = env::var(NAME);
env::set_var(NAME, "0");
let error = failure::err_msg("Hello!");
let resp: Error = error.into();
2018-04-13 23:02:01 +00:00
assert_eq!(
format!("{:?}", resp),
"Compat { error: ErrorMessage { msg: \"Hello!\" } }\n\n"
);
match old_tb {
Ok(x) => env::set_var(NAME, x),
_ => env::remove_var(NAME),
}
}
#[test]
fn test_internal_error() {
let err = InternalError::from_response(
ExpectError::Encoding, HttpResponse::Ok().into());
let resp: HttpResponse = err.error_response();
assert_eq!(resp.status(), StatusCode::OK);
}
2017-10-07 04:48:14 +00:00
}