apollo-errors-derive 0.4.0

Proc macro for deriving apollo-errors::Error trait
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
//! Tests for the Error derive macro using insta snapshots

use super::{codegen, parse};

fn pretty_print(tokens: proc_macro2::TokenStream) -> String {
    let file = syn::parse2(tokens).expect("valid tokens");
    prettyplease::unparse(&file)
}

/// Derive Error for an enum (for testing)
fn derive_error_enum(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let ir = parse::parse_error_derive(input)?;
    Ok(codegen::generate(&ir))
}

/// Derive Error for a struct (for testing)
fn derive_error_struct(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let ir = parse::parse_error_derive(input)?;
    Ok(codegen::generate(&ir))
}

mod expansion {
    use super::*;

    mod enums {
        use super::*;

        #[test]
        fn simple() {
            let output = derive_error_enum(syn::parse_quote! {
                enum SimpleError {
                    #[error("Something went wrong")]
                    #[diagnostic(code(errors::simple))]
                    Simple,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_fields() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithFields {
                    #[error("Invalid port")]
                    #[diagnostic(code(config::invalid_port))]
                    InvalidPort {
                        #[extension]
                        port: u16,

                        #[extension]
                        config_file: String,
                    },
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_help() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithHelp {
                    #[error("Invalid configuration")]
                    #[diagnostic(code(config::invalid), help("Check your configuration file for syntax errors"))]
                    InvalidConfig,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_http_status() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithHttpStatus {
                    #[error("Resource not found")]
                    #[diagnostic(code(resource::not_found))]
                    #[http_status(404)]
                    NotFound,

                    #[error("Unauthorized access")]
                    #[diagnostic(code(auth::unauthorized))]
                    #[http_status(401)]
                    Unauthorized,

                    #[error("Internal server error")]
                    #[diagnostic(code(server::internal))]
                    InternalError,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_severity() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithSeverity {
                    #[error("Deprecated API usage")]
                    #[diagnostic(code(api::deprecated), severity(Warning))]
                    DeprecatedApi,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_url() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithUrl {
                    #[error("Database connection failed")]
                    #[diagnostic(code(db::connection_failed), url("https://docs.example.com/errors/db-connection"))]
                    ConnectionFailed,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn multiple_variants() {
            let output = derive_error_enum(syn::parse_quote! {
                enum MultiError {
                    #[error("First error")]
                    #[diagnostic(code(multi::first))]
                    First,

                    #[error("Second error with field")]
                    #[diagnostic(code(multi::second))]
                    Second {
                        #[extension]
                        value: i32,
                    },

                    #[error("Third error")]
                    #[diagnostic(code(multi::third), help("Try something else"))]
                    #[http_status(400)]
                    Third,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_source() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithSource {
                    #[error("IO error occurred")]
                    #[diagnostic(code(io::error))]
                    IoError {
                        #[source]
                        source: std::io::Error,
                    },
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn transparent_variant() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithTransparent {
                    #[error("Regular error")]
                    #[diagnostic(code(errors::regular))]
                    Regular,

                    #[diagnostic(transparent)]
                    Inner(std::io::Error),
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn with_from() {
            let output = derive_error_enum(syn::parse_quote! {
                enum ErrorWithFrom {
                    #[error("IO error")]
                    #[diagnostic(code(io::error))]
                    Io {
                        #[from]
                        source: std::io::Error,
                    },
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }
    }

    mod structs {
        use super::*;

        #[test]
        fn simple_struct() {
            let output = derive_error_struct(syn::parse_quote! {
                #[error("Something went wrong")]
                #[diagnostic(code(errors::struct_error))]
                struct SimpleStructError;
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn struct_with_fields() {
            let output = derive_error_struct(syn::parse_quote! {
                #[error("Invalid configuration")]
                #[diagnostic(code(config::invalid))]
                struct ConfigError {
                    #[extension]
                    field: String,
                    #[extension]
                    line: u32,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn struct_with_help() {
            let output = derive_error_struct(syn::parse_quote! {
                #[error("Missing required field")]
                #[diagnostic(code(validation::missing_field), help("Ensure all required fields are provided"))]
                struct MissingFieldError {
                    #[extension]
                    field_name: String,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn struct_with_http_status() {
            let output = derive_error_struct(syn::parse_quote! {
                #[error("Not found")]
                #[diagnostic(code(http::not_found))]
                #[http_status(404)]
                struct NotFoundError {
                    #[extension]
                    resource: String,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }

        #[test]
        fn struct_with_source() {
            let output = derive_error_struct(syn::parse_quote! {
                #[error("Database error")]
                #[diagnostic(code(db::error))]
                struct DbError {
                    #[source]
                    source: std::io::Error,
                }
            })
            .unwrap();

            insta::assert_snapshot!(pretty_print(output));
        }
    }
}

mod errors {
    use super::*;

    #[test]
    fn union_not_supported() {
        let result = derive_error_enum(syn::parse_quote! {
            union NotSupported {
                a: u32,
                b: f32,
            }
        });

        let Err(err) = result else {
            panic!("union should return error");
        };
        assert!(err.to_string().contains("cannot be used on unions"));
    }

    #[test]
    fn error_code_too_few_segments() {
        let result = derive_error_enum(syn::parse_quote! {
            enum MyError {
                #[error("Bad code")]
                #[diagnostic(code(just_one))]
                Bad,
            }
        });

        let Err(err) = result else {
            panic!("too few segments should return error");
        };
        assert!(err.to_string().contains("at least 2 segments"));
    }

    #[test]
    fn error_code_uppercase_rejected() {
        let result = derive_error_enum(syn::parse_quote! {
            enum MyError {
                #[error("Bad code")]
                #[diagnostic(code(TEST::UPPERCASE))]
                Bad,
            }
        });

        let Err(err) = result else {
            panic!("uppercase code should return error");
        };
        assert!(err.to_string().contains("lowercase"));
    }

    #[test]
    fn optional_field_in_enum_message_rejected() {
        let result = derive_error_enum(syn::parse_quote! {
            enum MyError {
                #[error("Retry after {retry_after}")]
                #[diagnostic(code(rate::limited))]
                RateLimited {
                    retry_after: Option<u64>,
                },
            }
        });

        let Err(err) = result else {
            panic!("optional field in message should return error");
        };
        assert!(
            err.to_string()
                .contains("optional field `retry_after` cannot be used in error message")
        );
    }

    #[test]
    fn optional_field_in_struct_message_rejected() {
        let result = derive_error_struct(syn::parse_quote! {
            #[error("Error at line {line}")]
            #[diagnostic(code(parse::error))]
            struct ParseError {
                line: Option<u32>,
            }
        });

        let Err(err) = result else {
            panic!("optional field in message should return error");
        };
        assert!(
            err.to_string()
                .contains("optional field `line` cannot be used in error message")
        );
    }

    #[test]
    fn optional_field_not_in_message_allowed() {
        let result = derive_error_struct(syn::parse_quote! {
            #[error("Something went wrong")]
            #[diagnostic(code(errors::test))]
            struct TestError {
                #[extension]
                context: Option<String>,
            }
        });

        assert!(
            result.is_ok(),
            "optional field not in message should be allowed"
        );
    }

    #[test]
    fn non_optional_field_in_message_allowed() {
        let result = derive_error_struct(syn::parse_quote! {
            #[error("Invalid value: {value}")]
            #[diagnostic(code(errors::invalid))]
            struct InvalidError {
                value: String,
            }
        });

        assert!(
            result.is_ok(),
            "non-optional field in message should be allowed"
        );
    }
}