Giter Club home page Giter Club logo

errors's People

Contributors

alexandear avatar artemseleznev avatar casualjim avatar dependabot[bot] avatar fiorix avatar fredbi avatar gautierdelorme avatar guillemj avatar ligustah avatar maxatome avatar simon-li avatar ujjwalsh avatar youyuanwu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

errors's Issues

Useful code in Validation errors?

Hi, I came across this package, as I am auto-generating my input and output models using go-swagger. This is very nice, as I am able to generate my parsing and validation logic from the same source as my documentation, making the design -> documentation <-> development workflow very streamlined. So, first off, thanks for all the hard work you all have done to make such a useful toolkit.

However, I came across a usability issue with the errors, I would like to address, but would like feedback before making a fork. In short, the error code for all validation errors is exactly the same (422), which is problematic, when I want to generate custom validation errors in our api. Our api returns validation erros for each field with an error code, which is translated in the frontend (javascript SPA, iOS app). We use one error code for required, one for duplicate, one for must be true, one for invalid length, one for invalid data, etc... So, I was writing some code to translate the go-openapi/errors/Validation type into our custom type. But there is no easy way to introspect an error to find its cause.

Basically, my input validation code (auto-generated by go-swagger) looks something like this:

// Validate validates this create link params
func (m *CreateLinkParams) Validate(formats strfmt.Registry) error {
    var res []error
    if err := m.validateDestID(formats); err != nil {
        // prop
        res = append(res, err)
    }
        // ... validate other fields ....
    if len(res) > 0 {
        return errors.CompositeValidationError(res...)
    }
    return nil
}

func (m *CreateLinkParams) validateDestID(formats strfmt.Registry) error {
    if err := validate.Required("dest_id", "body", m.DestID); err != nil {
        return err
    }
    return nil
}

validate.Required (from go-openapi/validate) is this:

// Required validates an interface for requiredness
func Required(path, in string, data interface{}) *errors.Validation {
    val := reflect.ValueOf(data)
    if val.IsValid() {
        if reflect.DeepEqual(reflect.Zero(val.Type()).Interface(), val.Interface()) {
            return errors.Required(path, in)
        }
        return nil
    }
    return errors.Required(path, in)
}

and errors.Required (from go-openapi/errors) is this:

// Required error for when a value is missing
func Required(name, in string) *Validation {
    var msg string
    if in == "" {
        msg = fmt.Sprintf(requiredFailNoIn, name)
    } else {
        msg = fmt.Sprintf(requiredFail, name, in)
    }
    return &Validation{
        code:    422,
        Name:    name,
        In:      in,
        message: msg,
    }
}

Name gives me the field name that has an error (very nice), In is always body for parsing POST/PUT body, message (returned by Error()) is some text that does depend on the error type, and code (returned by Code()) is always 422 for every error.

I now have three approaches.

  1. Just refer to any field that fails validation as invalid, giving the error message as extra context, which makes our response not so useful and not translatable.
  2. Try to parse out the Error() text to figure out if it is a required, too long, etc. error. Adn then set the proper error code. This is possible but ugly and error-prone.
  3. Attach some useful code variable to each different type of Validation error that could be used by a switch statement to determine the type (ideally as a set of exportyed named constants form the errors package.

The third choice seems the most stable, extensible, and useful for me and others, but I don't know if this would break some other package. Or if there was a conscious decision to use this http error code here?

If you like the approach, I would be happy to prepare a pull request with approach number 3

Cheers,
Ethan

Add support for ValidateName to CompositeError

Validation contains a helper method ValidateName that extends the error message with an additional name that's used to generate better error messages for nested properties.

With CompositeError this isn't possible and results in ambiguous error messages. For consistency in the API CompositeError should be updated to include a ValidateName method that recursively calls ValidateName on any children.

Open Question:

  • Should this happen recursively by calling ValidateName on any CompositeError objects included in the root CompositeError?

Build failure

github.com/go-openapi/validate

../../github.com/go-openapi/validate/object_validator.go:75:34: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})
../../github.com/go-openapi/validate/object_validator.go:91:34: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})

Question: ServeError type switch

I am wondering how we may produce a testcase to enter this type type switch branch here:

errors/api.go

Line 128 in 7bcb96a

if e == nil {

I assume the intent is to detect a nil pointer on a type implementing the Error interface{}, but it looks like things don't work that way...

In my opinion, really guarding against nil here would involve some reflection, with something like:
reflect.ValueOf(e).IsNil() when reflect.TypeOf(e) is a nillable type...

I did not feel like polluting the code with reflection so I gave up. But the question is still itching...
Similar type switches do exist in the validate package, which I consistently failed to explore with valid test cases...

Please advise.

My build fails

With the following error.

not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})

Tag 0.19.6 is not compatible with v0.23 of go-swagger generated codegot

Using go-swagger v0.23. Generated my server code. Did go get ./... The latest tag of this package is generating errors in the build. I had to back it down to 0.19.4 to get the generated code to compile. It looks like the Required function has changed arguments. Build Errors:

Here is a few lines of the the build errors seen:

restapi/operations/classifier/post_classifier_parameters.go:56:38: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})
restapi/operations/classifier/post_classifier_parameters.go:71:36: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})
restapi/operations/classifier/update_classifier_by_id_parameters.go:62:38: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})
restapi/operations/classifier/update_classifier_by_id_parameters.go:77:36: not enough arguments in call to "github.com/go-openapi/errors".Required
have (string, string)
want (string, string, interface {})

Proposal: Ability to JSON errors with private fields

Hello.
It would be very useful to have a builtin way to Marshal and Unmarshal validation errors completely (including fields "code" and "message"). This feature will allow us to send validation errors directly to API clients without wrapping them, etc.
I see the following 2 ways to implement it:

  1. Make "code" and "message" public. This makes uncontrollable changes to be possible.
  2. Add custom marshaling/unmarshaling to error structs like this:
func (e *Validation) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"code": e.code,
		"name": e.Name,
		"in": e.In,
		"value": e.Value,
		"message": e.message,
		"values": e.Values,
	})
}

func (e *Validation) UnmarshalJSON(data []byte) error {
	theMap := make(map[string]interface{})
	err := json.Unmarshal(data, theMap)
	if err != nil {
		return err
	}

	e.code = theMap["code"].(int32)
	e.Name = theMap["name"].(string)
	e.In = theMap["in"].(string)
	e.Value = theMap["value"]
	e.message = theMap["message"].(string)
	e.Values = theMap["values"].([]interface{})
	return nil
}

Could you implement this feature, please?
Thank you in advance.

Add MultipleOf factor must be positive

Now go-openapi/validate insures the MultipleOf factor must be positive as required by spec [strange that it does not pops up at json-schema validation time]

Suggest an additional generic message for that here.

P.R following up.

Security Vulnerability

Security vulnerability in package:

gopkg.in/yaml.v3 is a YAML support package for the Go language.

Affected versions of this package are vulnerable to NULL Pointer Dereference when parsing #\n-\n-\n0 via the parserc.go parser.

Fixed in: gopkg.in/[email protected]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.