Skip to content

Commit

Permalink
Merge pull request #200 from redbadger/http-error-display
Browse files Browse the repository at this point in the history
  • Loading branch information
StuartHarris authored Feb 3, 2024
2 parents 1b6b3fe + 8664764 commit 28b5a9f
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crux_http/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ pub struct Error {
code: Option<crate::http::StatusCode>,
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(code) = self.code {
write!(f, "{}: {}", code, self.message)
} else {
write!(f, "{}", self.message)
}
}
}

impl Error {
pub fn new(code: Option<crate::http::StatusCode>, message: impl Into<String>) -> Self {
Error {
Expand Down Expand Up @@ -39,3 +49,17 @@ impl From<url::ParseError> for Error {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_error_display() {
let error = Error::new(Some(crate::http::StatusCode::BadRequest), "Bad Request");
assert_eq!(error.to_string(), "400: Bad Request");

let error = Error::new(None, "internal server error");
assert_eq!(error.to_string(), "internal server error");
}
}

0 comments on commit 28b5a9f

Please sign in to comment.