use std::fmt;
use http::StatusCode;
use http::header::{HeaderValue, SEC_WEBSOCKET_VERSION};
pub use super::path::PathErrorKind;
use crate::AppError;
use crate::body::BodyError;
use crate::response::{IntoResponse, Response};
macro_rules! rejection {
($($name:ident),* $(,)?) => {
$(
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.body_text())
}
}
impl std::error::Error for $name {}
impl IntoResponse for $name {
fn into_response(self) -> Response {
self.to_app_error().into_response()
}
}
impl $name {
pub fn to_app_error(&self) -> AppError {
AppError::rejection(self.status(), self.body_text())
}
}
)*
};
}
rejection!(
PathRejection,
QueryRejection,
FormRejection,
JsonRejection,
ExtensionRejection,
MultipartRejection,
MultipartError,
);
#[derive(Debug)]
pub struct PathRejection(pub(crate) PathErrorKind);
impl PathRejection {
pub fn kind(&self) -> &PathErrorKind {
&self.0
}
pub fn status(&self) -> StatusCode {
self.0.status()
}
pub fn body_text(&self) -> String {
if self.status().is_client_error() {
format!("Invalid URL: {}", self.0)
} else {
self.0.to_string()
}
}
}
#[derive(Debug)]
pub struct QueryRejection(pub(crate) String);
impl QueryRejection {
pub fn status(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
pub fn body_text(&self) -> String {
format!("Failed to deserialize query string: {}", self.0)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum FormRejection {
ContentType,
Body(BodyError),
Query(String),
Deserialize(String),
}
impl FormRejection {
pub fn status(&self) -> StatusCode {
match self {
FormRejection::ContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
FormRejection::Body(error) => error.status(),
FormRejection::Query(_) | FormRejection::Deserialize(_) => StatusCode::BAD_REQUEST,
}
}
pub fn body_text(&self) -> String {
match self {
FormRejection::ContentType => {
"Form requests must have `Content-Type: application/x-www-form-urlencoded`"
.to_owned()
}
FormRejection::Body(error) => error.to_string(),
FormRejection::Query(error) => format!("Failed to deserialize form: {error}"),
FormRejection::Deserialize(error) => {
format!("Failed to deserialize form body: {error}")
}
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum JsonRejection {
ContentType,
Body(BodyError),
Syntax(String),
Data(String),
}
impl JsonRejection {
pub fn status(&self) -> StatusCode {
match self {
JsonRejection::ContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
JsonRejection::Body(error) => error.status(),
JsonRejection::Syntax(_) | JsonRejection::Data(_) => StatusCode::BAD_REQUEST,
}
}
pub fn body_text(&self) -> String {
match self {
JsonRejection::ContentType => {
"Expected request with `Content-Type: application/json`".to_owned()
}
JsonRejection::Body(error) => error.to_string(),
JsonRejection::Syntax(error) => {
format!("Failed to parse the request body as JSON: {error}")
}
JsonRejection::Data(error) => {
format!("Failed to deserialize the JSON body into the target type: {error}")
}
}
}
}
#[derive(Debug)]
pub struct ExtensionRejection(pub(crate) &'static str);
impl ExtensionRejection {
pub fn status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
pub fn body_text(&self) -> String {
format!(
"Missing request extension: Extension of type `{}` was not found",
self.0
)
}
}
#[derive(Debug)]
pub struct MultipartRejection;
impl MultipartRejection {
pub fn status(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
pub fn body_text(&self) -> String {
"Invalid `boundary` for `multipart/form-data` request".to_owned()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum MultipartError {
TooManyParts {
limit: usize,
},
FieldTooLarge {
limit: u64,
},
FileTooLarge {
limit: u64,
},
HeadTooLarge {
limit: usize,
},
Body(BodyError),
Malformed(String),
}
impl MultipartError {
pub fn status(&self) -> StatusCode {
match self {
MultipartError::TooManyParts { .. }
| MultipartError::FieldTooLarge { .. }
| MultipartError::FileTooLarge { .. }
| MultipartError::HeadTooLarge { .. } => StatusCode::PAYLOAD_TOO_LARGE,
MultipartError::Body(error) => error.status(),
MultipartError::Malformed(_) => StatusCode::BAD_REQUEST,
}
}
pub fn body_text(&self) -> String {
match self {
MultipartError::TooManyParts { limit } => {
format!("A form may have at most {limit} parts")
}
MultipartError::FieldTooLarge { limit } => {
format!("A form field may have at most {limit} bytes")
}
MultipartError::FileTooLarge { limit } => {
format!("A file may have at most {limit} bytes")
}
MultipartError::HeadTooLarge { limit } => {
format!("The headers of a form part may have at most {limit} bytes")
}
MultipartError::Body(BodyError::TooLarge) => "Request payload is too large".to_owned(),
MultipartError::Body(error) => error.to_string(),
MultipartError::Malformed(error) => error.clone(),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WebSocketRejection {
HttpVersion,
MethodNotGet,
MethodNotConnect,
Connection,
Upgrade,
Protocol,
Version,
KeyMissing,
Key,
NotUpgradable,
}
impl WebSocketRejection {
pub fn status(&self) -> StatusCode {
match self {
WebSocketRejection::MethodNotGet | WebSocketRejection::MethodNotConnect => {
StatusCode::METHOD_NOT_ALLOWED
}
WebSocketRejection::NotUpgradable => StatusCode::UPGRADE_REQUIRED,
_ => StatusCode::BAD_REQUEST,
}
}
pub fn body_text(&self) -> String {
match self {
WebSocketRejection::HttpVersion => "WebSockets need HTTP/1.1 or later",
WebSocketRejection::MethodNotGet => "Request method must be `GET`",
WebSocketRejection::MethodNotConnect => "Request method must be `CONNECT`",
WebSocketRejection::Connection => "Connection header did not include 'upgrade'",
WebSocketRejection::Upgrade => "`Upgrade` header did not include 'websocket'",
WebSocketRejection::Protocol => "`:protocol` pseudo-header did not include 'websocket'",
WebSocketRejection::Version => "`Sec-WebSocket-Version` header did not include '13'",
WebSocketRejection::KeyMissing => "`Sec-WebSocket-Key` header missing",
WebSocketRejection::Key => "`Sec-WebSocket-Key` must be the base64 of 16 bytes",
WebSocketRejection::NotUpgradable => {
"WebSocket request couldn't be upgraded since no upgrade state was present"
}
}
.to_owned()
}
pub fn to_app_error(&self) -> AppError {
let error = AppError::rejection(self.status(), self.body_text());
match self {
WebSocketRejection::Version => {
error.with_header(SEC_WEBSOCKET_VERSION, HeaderValue::from_static("13"))
}
_ => error,
}
}
}
impl fmt::Display for WebSocketRejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.body_text())
}
}
impl std::error::Error for WebSocketRejection {}
impl IntoResponse for WebSocketRejection {
fn into_response(self) -> Response {
self.to_app_error().into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejections_render_in_the_error_format() {
let error = JsonRejection::ContentType.to_app_error();
assert_eq!(error.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert_eq!(
error.body(),
serde_json::json!({
"statusCode": 415,
"message": "Expected request with `Content-Type: application/json`",
"error": "Unsupported Media Type",
"code": "unsupported_media_type",
})
);
let error = FormRejection::Body(BodyError::TooLarge).to_app_error();
assert_eq!(error.status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
error.body()["message"],
"Failed to buffer the request body: length limit exceeded"
);
let error = ExtensionRejection("navree_kernel::AppContext").to_app_error();
assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(error.body()["message"], "Internal server error");
assert!(error.log_chain().contains("AppContext"), "logged");
let error = PathRejection(PathErrorKind::ParseError {
value: "x".into(),
expected_type: "u32",
});
assert_eq!(
error.to_string(),
"Invalid URL: Cannot parse `x` to a `u32`"
);
assert_eq!(
QueryRejection("page: invalid digit found in string".into()).to_string(),
"Failed to deserialize query string: page: invalid digit found in string"
);
}
}