autumn-web 0.2.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Framework error type and result alias.
//!
//! [`AutumnError`] wraps any `Error + Send + Sync` with an HTTP status code.
//! The blanket [`From`] impl maps all errors to `500 Internal Server Error`,
//! so the `?` operator works in handlers with zero ceremony.
//!
//! For non-500 cases, use the status refinement constructors:
//!
//! - [`AutumnError::not_found`] -- 404
//! - [`AutumnError::bad_request`] -- 400
//! - [`AutumnError::unprocessable`] -- 422
//! - [`AutumnError::service_unavailable`] -- 503
//! - [`AutumnError::with_status`] -- arbitrary status code
//!
//! For simple string messages without wrapping an error type:
//!
//! - [`AutumnError::not_found_msg`] -- 404 with a message
//! - [`AutumnError::bad_request_msg`] -- 400 with a message
//! - [`AutumnError::unprocessable_msg`] -- 422 with a message
//! - [`AutumnError::service_unavailable_msg`] -- 503 with a message
//!
//! # Response format
//!
//! When an `AutumnError` is returned from a handler, it renders as JSON:
//!
//! ```json
//! { "error": { "status": 404, "message": "user not found" } }
//! ```
//!
//! # Examples
//!
//! ```rust
//! use autumn_web::error::AutumnError;
//! use http::StatusCode;
//!
//! // Blanket From impl: any Error becomes 500
//! let err: AutumnError = std::io::Error::other("disk full").into();
//! assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
//!
//! // Explicit status constructors
//! let err = AutumnError::not_found(std::io::Error::other("no such user"));
//! assert_eq!(err.status(), StatusCode::NOT_FOUND);
//! ```

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;

/// Simple error type wrapping a string message.
///
/// Used by the `_msg` convenience constructors on [`AutumnError`] so callers
/// don't need to wrap strings in `std::io::Error`.
#[derive(Debug)]
struct StringError(String);

impl std::fmt::Display for StringError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for StringError {}

/// Typed JSON body for error responses -- avoids dynamic `serde_json::Value`.
#[derive(Serialize)]
struct ErrorBody {
    error: ErrorInner,
}

#[derive(Serialize)]
struct ErrorInner {
    status: u16,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    details: Option<std::collections::HashMap<String, Vec<String>>>,
}

/// Framework error type wrapping any error with an HTTP status code.
///
/// # Usage
///
/// The `?` operator converts any `std::error::Error` into an `AutumnError`
/// with status `500 Internal Server Error`:
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn handler() -> AutumnResult<&'static str> {
///     autumn_web::reexports::tokio::fs::read_to_string("missing.txt").await?; // becomes 500 on error
///     Ok("ok")
/// }
/// ```
///
/// For expected errors, use a status refinement constructor:
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// async fn get_user(axum::extract::Path(id): axum::extract::Path<i32>) -> AutumnResult<String> {
///     if id < 0 {
///         return Err(AutumnError::bad_request(
///             std::io::Error::other("id must be positive"),
///         ));
///     }
///     Ok(format!("user {id}"))
/// }
/// ```
///
/// # Why no `Error` impl
///
/// `AutumnError` intentionally does **not** implement [`std::error::Error`].
/// Doing so would conflict with the blanket `From<E: Error>` impl (the
/// reflexive `From<T> for T` would overlap). This type is a *response*
/// wrapper, not a propagatable error.
pub struct AutumnError {
    inner: Box<dyn std::error::Error + Send + Sync>,
    status: StatusCode,
    details: Option<std::collections::HashMap<String, Vec<String>>>,
}

/// Convenience alias -- the standard return type for Autumn handlers.
///
/// Equivalent to `Result<T, AutumnError>`. Use this as the return type
/// for any handler that might fail.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> AutumnResult<&'static str> {
///     Ok("hello")
/// }
/// ```
pub type AutumnResult<T> = Result<T, AutumnError>;

impl<E> From<E> for AutumnError
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn from(err: E) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::INTERNAL_SERVER_ERROR,
            details: None,
        }
    }
}

impl AutumnError {
    /// Override the HTTP status code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err: AutumnError = std::io::Error::other("forbidden").into();
    /// let err = err.with_status(StatusCode::FORBIDDEN);
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    #[must_use]
    pub const fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    /// Create a `500 Internal Server Error`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::internal_server_error(std::io::Error::other("boom"));
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    pub fn internal_server_error(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::INTERNAL_SERVER_ERROR,
            details: None,
        }
    }

    /// Create a `404 Not Found` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::not_found(std::io::Error::other("no such user"));
    /// assert_eq!(err.status(), StatusCode::NOT_FOUND);
    /// ```
    pub fn not_found(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::NOT_FOUND,
            details: None,
        }
    }

    /// Create a `400 Bad Request` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::bad_request(std::io::Error::other("invalid input"));
    /// assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    /// ```
    pub fn bad_request(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::BAD_REQUEST,
            details: None,
        }
    }

    /// Create a `422 Unprocessable Entity` error.
    ///
    /// Use this for validation failures where the request is syntactically
    /// valid but semantically incorrect.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unprocessable(std::io::Error::other("age must be positive"));
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    pub fn unprocessable(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::UNPROCESSABLE_ENTITY,
            details: None,
        }
    }

    /// Create a `503 Service Unavailable` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::service_unavailable(std::io::Error::other("pool exhausted"));
    /// assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    /// ```
    pub fn service_unavailable(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::SERVICE_UNAVAILABLE,
            details: None,
        }
    }

    /// Create a `401 Unauthorized` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unauthorized(std::io::Error::other("not logged in"));
    /// assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    /// ```
    pub fn unauthorized(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::UNAUTHORIZED,
            details: None,
        }
    }

    /// Create a `403 Forbidden` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::forbidden(std::io::Error::other("not allowed"));
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    pub fn forbidden(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::FORBIDDEN,
            details: None,
        }
    }

    /// Create a `422 Unprocessable Entity` error with field-level
    /// validation details.
    ///
    /// Use this when a request fails multiple field-specific validation rules
    /// (e.g., in a form submission). It attaches the `details` parameter, a mapping
    /// of field names to their respective error messages, so the client can display
    /// errors next to the relevant inputs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    /// use std::collections::HashMap;
    ///
    /// let mut errors = HashMap::new();
    /// errors.insert("username".to_string(), vec!["Username is taken".to_string()]);
    ///
    /// let err = AutumnError::validation(errors);
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    #[must_use]
    pub fn validation(details: std::collections::HashMap<String, Vec<String>>) -> Self {
        Self {
            inner: Box::new(StringError("Validation failed".into())),
            status: StatusCode::UNPROCESSABLE_ENTITY,
            details: Some(details),
        }
    }

    // ── String-message convenience constructors ────────────────

    /// Create a `500 Internal Server Error` from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::internal_server_error_msg("Database explosion");
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    pub fn internal_server_error_msg(msg: impl Into<String>) -> Self {
        Self::internal_server_error(StringError(msg.into()))
    }

    /// Create a `404 Not Found` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::not_found_msg("No such user");
    /// assert_eq!(err.status(), StatusCode::NOT_FOUND);
    /// assert_eq!(err.to_string(), "No such user");
    /// ```
    pub fn not_found_msg(msg: impl Into<String>) -> Self {
        Self::not_found(StringError(msg.into()))
    }

    /// Create a `400 Bad Request` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::bad_request_msg("Invalid input parameter");
    /// assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    /// ```
    pub fn bad_request_msg(msg: impl Into<String>) -> Self {
        Self::bad_request(StringError(msg.into()))
    }

    /// Create a `422 Unprocessable Entity` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unprocessable_msg("Title is required");
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    pub fn unprocessable_msg(msg: impl Into<String>) -> Self {
        Self::unprocessable(StringError(msg.into()))
    }

    /// Create a `401 Unauthorized` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unauthorized_msg("Please log in to continue");
    /// assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    /// ```
    pub fn unauthorized_msg(msg: impl Into<String>) -> Self {
        Self::unauthorized(StringError(msg.into()))
    }

    /// Create a `403 Forbidden` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::forbidden_msg("You lack admin privileges");
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    pub fn forbidden_msg(msg: impl Into<String>) -> Self {
        Self::forbidden(StringError(msg.into()))
    }

    /// Create a `503 Service Unavailable` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::service_unavailable_msg("Database connection pool exhausted");
    /// assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    /// ```
    pub fn service_unavailable_msg(msg: impl Into<String>) -> Self {
        Self::service_unavailable(StringError(msg.into()))
    }

    /// Returns the HTTP status code associated with this error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err: AutumnError = std::io::Error::other("boom").into();
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    #[must_use]
    pub const fn status(&self) -> StatusCode {
        self.status
    }
}

impl std::fmt::Display for AutumnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl std::fmt::Debug for AutumnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AutumnError")
            .field("status", &self.status)
            .field("inner", &self.inner)
            .field("details", &self.details)
            .finish()
    }
}

impl IntoResponse for AutumnError {
    fn into_response(self) -> Response {
        let status = self.status;
        let message = self.inner.to_string();

        // Stash error metadata for exception filters to inspect without
        // parsing the response body.
        let error_info = crate::middleware::AutumnErrorInfo {
            status,
            message: message.clone(),
            details: self.details.clone(),
        };

        let body = ErrorBody {
            error: ErrorInner {
                status: status.as_u16(),
                message,
                details: self.details,
            },
        };

        let mut response = (status, axum::Json(body)).into_response();
        response.extensions_mut().insert(error_info);
        response
    }
}

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

    #[derive(Debug)]
    struct TestError(String);

    impl std::fmt::Display for TestError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl std::error::Error for TestError {}

    #[test]
    fn blanket_from_defaults_to_500() {
        let err: AutumnError = TestError("boom".into()).into();
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn internal_server_error_is_500() {
        let err = AutumnError::internal_server_error(TestError("boom".into()));
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_not_found_error() {
        let err = AutumnError::not_found(std::io::Error::other("no such user"));
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn not_found_is_404() {
        let err = AutumnError::not_found(TestError("missing".into()));
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn bad_request_is_400() {
        let err = AutumnError::bad_request(TestError("invalid input".into()));
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn unprocessable_is_422() {
        let err = AutumnError::unprocessable(TestError("bad entity".into()));
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn unauthorized_is_401() {
        let err = AutumnError::unauthorized(TestError("unauthorized".into()));
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn forbidden_is_403() {
        let err = AutumnError::forbidden(TestError("forbidden".into()));
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn validation_is_422() {
        let mut details = std::collections::HashMap::new();
        details.insert("field".to_string(), vec!["error".to_string()]);
        let err = AutumnError::validation(details);
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn service_unavailable_is_503() {
        let err = AutumnError::service_unavailable(TestError("pool exhausted".into()));
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn internal_server_error_msg_is_500() {
        let err = AutumnError::internal_server_error_msg("db failure");
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.to_string(), "db failure");
    }

    #[test]
    fn not_found_msg_is_404() {
        let err = AutumnError::not_found_msg("no such user");
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.to_string(), "no such user");
    }

    #[test]
    fn bad_request_msg_is_400() {
        let err = AutumnError::bad_request_msg("invalid input");
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn unprocessable_msg_is_422() {
        let err = AutumnError::unprocessable_msg("title required");
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn unauthorized_msg_is_401() {
        let err = AutumnError::unauthorized_msg("login required");
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn forbidden_msg_is_403() {
        let err = AutumnError::forbidden_msg("no access");
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn service_unavailable_msg_is_503() {
        let err = AutumnError::service_unavailable_msg("db down");
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(err.to_string(), "db down");
    }

    #[test]
    fn with_status_overrides() {
        let err: AutumnError = TestError("forbidden".into()).into();
        let err = err.with_status(StatusCode::FORBIDDEN);
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn display_uses_inner_message() {
        let err: AutumnError = TestError("something broke".into()).into();
        assert_eq!(err.to_string(), "something broke");
    }

    #[test]
    fn into_response_has_correct_status() {
        let err = AutumnError::not_found(TestError("not found".into()));
        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn into_response_has_json_body() -> Result<(), axum::Error> {
        let err = AutumnError::not_found(TestError("not found".into()));
        let response = err.into_response();

        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");

        assert_eq!(json["error"]["status"], 404);
        assert_eq!(json["error"]["message"], "not found");
        Ok(())
    }

    #[test]
    fn debug_shows_status_and_inner() {
        let err = AutumnError::bad_request(TestError("oops".into()));
        let debug = format!("{err:?}");
        assert!(debug.contains("AutumnError"));
        assert!(debug.contains("400"));
    }

    #[tokio::test]
    async fn msg_constructor_produces_valid_json_response() -> Result<(), axum::Error> {
        let err = AutumnError::unprocessable_msg("title required");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");
        assert_eq!(json["error"]["status"], 422);
        assert_eq!(json["error"]["message"], "title required");
        Ok(())
    }

    #[tokio::test]
    async fn service_unavailable_response_is_503() -> Result<(), axum::Error> {
        let err = AutumnError::service_unavailable_msg("db down");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");
        assert_eq!(json["error"]["status"], 503);
        assert_eq!(json["error"]["message"], "db down");
        Ok(())
    }
}