discord-gophers / goapi-gen

This package contains a set of utilities for generating Go boilerplate code for services based on OpenAPI 3.0 API definitions
Apache License 2.0
137 stars 12 forks source link

Add ParamName into certain Errors #78

Closed diamondburned closed 2 years ago

diamondburned commented 2 years ago

This commit adds the ParameterError interface that extends error to add a ParameterName() method. This method is implemented by existing errors that are currently returned when a parameter has an error (e.g. InvalidParamFormatError).

To check from an error to see if that error was caused by a parameter, the user can write

func(w http.ResponseWriter, r *http.Request, err error) {
    if paramError, ok := err.(openapi.ParameterError); ok {
        // Specifically write a 400 response with the parameter name in
        // the body.
        writeParamError(w, r, 400, paramError.ParameterName(), err)
        return
    }
    writeError(w, r, 400, err)
}
diamondburned commented 2 years ago

cc @zacharyburkett