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
//! Typed, composable HTTP error sets for [axum], with OpenAPI generation through
//! [aide](https://docs.rs/aide).
//!
//! Instead of one large error enum per application, each function lists the exact HTTP status
//! codes it can return, as a tuple in its return type:
//!
//! ```rust
//! # use axum_error_sets::{ApiResult, codes::{NotFound, Unauthorized}};
//! async fn get_user() -> ApiResult<String, (Unauthorized, NotFound<String>)> {
//! # todo!()
//! // ...
//! }
//! ```
//!
//! Returning a status code that isn't in the set is a compile error, and with the `aide`
//! feature every status code in the set appears in the generated OpenAPI documentation.
//!
//! # Building blocks
//! - **Status codes.** Every 4xx and 5xx status code has a wrapper type in [`codes`], such as
//! [`NotFound<T>`](codes::NotFound). The wrapped value `T` is the response body and must
//! implement [`IntoResponse`]. It defaults to `()`, which means an empty body.
//! - **Error sets.** [`ApiResponse<S>`] is an error response whose status code is one of the
//! codes in the tuple `S`. [`ApiResult<T, S>`] is short for `Result<T, ApiResponse<S>>`.
//! - **`?` conversion.** Any status code `C` converts into `ApiResponse<S>` when `S` contains
//! `C`, so `?` works directly. The order of the codes in the tuple doesn't matter.
//! - **Wrapping errors.** [`ResultStatusExt`] adds methods to every `Result` for giving its
//! error a status code (`with_status`, `into_status`), changing it (`change_status`), or
//! changing the body (`map_status`, `map_status_into`).
//! - **Growing sets.** [`ApiResultExt::into_superset`] turns a result with a small error set
//! into one with a larger set, so functions with narrow sets can be called from functions
//! with wider ones.
//!
//! # Example
//! ```rust
//! use axum::Json;
//! use axum_error_sets::{
//! ApiResult, ApiResultExt as _, ResultStatusExt as _,
//! codes::{Internal, NotFound, Unauthorized},
//! };
//!
//! fn check_token(token: &str) -> Result<(), Unauthorized> {
//! if token.is_empty() {
//! return Err(Unauthorized(()));
//! }
//! Ok(())
//! }
//!
//! fn find_user(id: u32) -> ApiResult<String, (NotFound<String>,)> {
//! let name = lookup(id)
//! .ok_or("no such user")
//! // `&str` error -> `NotFound<String>`
//! .into_status::<NotFound, String>()?;
//! Ok(name)
//! }
//!
//! async fn get_user(
//! token: String,
//! id: u32,
//! ) -> ApiResult<Json<String>, (Unauthorized, NotFound<String>, Internal<String>)> {
//! // `Unauthorized` is in the set, so `?` converts it.
//! check_token(&token)?;
//!
//! // `(NotFound<String>,)` is a subset of this handler's set.
//! let name = find_user(id).into_superset()?;
//!
//! // A `String` error -> `Internal<String>`
//! let name = normalize(name).with_status::<Internal>()?;
//!
//! Ok(Json(name))
//! }
//! # fn lookup(_: u32) -> Option<String> { None }
//! # fn normalize(name: String) -> Result<String, String> { Ok(name) }
//! ```
//!
//! Returning a status code that isn't in the set doesn't compile:
//! ```rust,compile_fail
//! # use axum_error_sets::{ApiResult, codes::{Forbidden, NotFound}};
//! async fn handler() -> ApiResult<(), (NotFound,)> {
//! Err(Forbidden(()))?; // error: `(NotFound,): Contains<Forbidden>` is not satisfied
//! Ok(())
//! }
//! ```
//!
//! More examples are in the
//! [`examples`](https://github.com/jvdwrf/axum-error-sets/tree/main/examples) directory.
//!
//! # Responses
//! When an [`ApiResponse`] is returned, the response has the status code of the wrapper it was
//! created from, even if the body's own response sets a different status. The body's
//! [`IntoResponse`] runs as soon as the `ApiResponse` is created, not when the handler
//! returns. Standard axum behaves differently here, which matters if `into_response` has side
//! effects such as logging.
//!
//! # OpenAPI with `aide`
//! With the `aide` feature enabled, `ApiResponse<S>` implements [`aide::OperationOutput`]
//! whenever every body type in `S` does. Each status code in the set is then documented as a
//! response of the operation. This works for sets of up to 16 status codes.
//!
//! # Typed routing
//! [axum-typed-routing](https://docs.rs/axum-typed-routing) is a companion crate for
//! declaring a route's path and parameters next to its handler. With its `api_route` macro,
//! the handler's error set shows up in the generated OpenAPI documentation automatically.
//!
//! # Feature flags
//! - `aide`: implements [`aide::OperationOutput`] for [`ApiResponse`].
use ;
use ;
/// Short for `Result<T, ApiResponse<S>>`.
pub type ApiResult<T, S> = ;
/// An error response whose status code is one of the codes in the set `S`.
///
/// `S` is a tuple of status codes from [`codes`], for example
/// `ApiResponse<(NotFound<String>, Internal<Json<String>>)>`. Usually it is the error type of
/// a handler, written as `Result<T, ApiResponse<S>>` or [`ApiResult<T, S>`].
///
/// It implements:
/// - [`IntoResponse`], so it can be returned from axum handlers;
/// - `From<C>` for every status code `C` in `S`, so `?` converts status codes into it;
/// - `aide::OperationOutput`, when the `aide` feature is enabled and every body type in `S`
/// implements `OperationOutput`.
///
/// The body's [`IntoResponse`] runs when the `ApiResponse` is created, not when the handler
/// returns. See [Responses](crate#responses).
///
/// # Example
/// ```rust
/// # use axum_error_sets::{ApiResponse, codes::*};
/// async fn handler() -> Result<(), ApiResponse<(NotFound<String>, BadRequest<String>)>> {
/// Err(NotFound("no such item".to_string()).into())
/// }
/// ```
}
)+
// $(
// #[allow(unused)]
// #[cfg(feature = "utoipa")]
// impl<$($E),*> utoipa::IntoResponses for ApiResponse<($($E,)*)>
// where
// $(
// $E: StatusProvider<Inner: utoipa::ToSchema>,
// )*
// {
// fn responses() -> std::collections::BTreeMap<
// String,
// utoipa::openapi::RefOr<utoipa::openapi::Response>,
// > {
// let mut responses = utoipa::openapi::ResponsesBuilder::new();
// $({
// let name = < $E::Inner as utoipa::ToSchema >::name();
// let schema = < $E::Inner as utoipa::PartialSchema >::schema();
// let content = utoipa::openapi::ContentBuilder::new()
// .schema(Some(schema))
// .build();
// responses = responses.response(
// $E::STATUS_CODE.as_u16().to_string(),
// utoipa::openapi::response::ResponseBuilder::new()
// .description(format!(
// "{} response for {}",
// $E::STATUS_CODE.as_u16(),
// name
// ))
// .content(
// "application/json",
// content
// )
// .build()
// );
// })*
// responses.build().responses
// }
// }
// )+
};
}
utoipa_aide_impls!;
/// A wrapper type that pairs a body with a fixed HTTP status code.
///
/// This trait is implemented for every status code in [`codes`]. The status code is part of
/// the type, which is what lets [`ApiResponse`] track which codes a handler can return.
/// Methods on any `Result` for giving its error an HTTP status code, and for changing the
/// status code or body of an error that already has one.
///
/// Each method only changes the `Err` value. `Ok` values pass through unchanged.
/// Methods on `Result<T, ApiResponse<S>>`.