Skip to content

Introduce an error for invalid enum values to distinguish 400 and 422 responses during JSON parsing #110

@aklinkert

Description

@aklinkert

Hello there! 👋🏻

When passing an invalid enum value to a JSON field using the enum type an untyped / unwrapped error is thrown:

return 0, fmt.Errorf("%%s does not belong to %[1]s values", s)

This makes distinguishing harder between an actual 400 response (body is not parsable) and a 422 (the data you passed are wrong) response.

Would you be up to introducing a typed error, that can be identified using errors.Is() and eventually accepting a PR for that?

As of right now, as a workaround, I am parsing the error string while setting the response status code as follows:

status := 400
enumerErrorStringMatcher := regexp.MustCompile(`^"\w+ does not belong to \w+ values"$`)

if enumerErrorStringMatcher.MatchString(err.Error()) {
	status = http.StatusUnprocessableEntity
}

Cheers,
Alex

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions