Something went wrong. Try again.
Integration between axum, thiserror and schemars
Something went wrong. Try again.
1.4 kB · 42 lines
Rust
at main
12345678910111213141516171819202122232425262728293031323334353637383940414243use axum::{http::StatusCode, response::IntoResponse};use axum_thiserror::ErrorStatus;use thiserror::Error;
#[derive(Error, Debug, ErrorStatus)]#[cfg_attr(feature = "json", derive(serde::Serialize))]#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]pub enum UserCreateError { #[error("Invalid email {email}")] #[status(StatusCode::UNAUTHORIZED)] InvalidEmail { email: String }, #[error("User {0} already exists with email")] #[status(StatusCode::CONFLICT)] UserAlreadyExists(String, String),}
#[test]fn basic_error() { let error = UserCreateError::InvalidEmail { email: "user01".to_string(), }; let response = error.into_response(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let error = UserCreateError::UserAlreadyExists("user01".to_string(), "email".to_string()); let response = error.into_response(); assert_eq!(response.status(), StatusCode::CONFLICT);}
#[cfg(not(feature = "json"))]#[tokio::test]async fn text_body() { let error = UserCreateError::InvalidEmail { email: "user01".to_string(), }; let response = error.into_response(); let body = axum::body::to_bytes(response.into_body(), usize::MAX) .await .unwrap(); assert_eq!(&body[..], b"Invalid email user01");}