Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom error codes #105

Open
jprochazk opened this issue Mar 29, 2024 · 3 comments
Open

Support custom error codes #105

jprochazk opened this issue Mar 29, 2024 · 3 comments

Comments

@jprochazk
Copy link
Owner

jprochazk commented Mar 29, 2024

Two parts:

  1. Add a code: Option<Cow<'static, str>> field to garde::Error

  2. Add a way to set the code for a specific rule via the proc macro.

The unresolved question here is syntax:

Option A:

#[garde(length(min = 1, code = "custom_error_code"))]

Option B:

#[garde(code("custom_error_code", length(min = 1)))]

(A) would require some hacks to "intercept" the code value during parsing. Both would work by intercepting the error returned by a rule and set its code field in the proc macro output. (B) seems easier to implement, but those coming from validator likely expect (A).

@lasantosr
Copy link
Contributor

lasantosr commented Mar 30, 2024

I think either (A) or (B) are good to go, as long as different rules can set different codes, it doesn't matter that much the syntax that's more similar to validator.

It must support both with and without code tho, so maybe the (A) its easier to understand in those cases.

btw, https://github.com/TedDriggs/darling might help with attribute parsing

@boyswan
Copy link

boyswan commented Jul 3, 2024

Based on:
#[garde(length(min = 1, code = "custom_error_code"))]

Would there be a way to also dynamically capture the criteria? The code is helpful, but in the real world it you really need to know what min is. However I imagine it would be tricky to know how or where to add this to the error struct.

I'm spitballing, but perhaps something along the lines of criteria: HashMap<(String, String), Value> which would equate to HashMap<("length", "min"), Value::Number(1)>>. I'm sure there's plenty reasons why this is wrong/won't work - but hopefully you get the idea!

Custom codes/messages is the one feature that is preventing be being able to migrate my validation to garde - I'd be really happy to see this!

@jprochazk
Copy link
Owner Author

There's an issue open for serializing constraints, which are rules + their inputs:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants