go-macaron / binding

Package binding is a middleware that provides request data binding and validation for Macaron.
Apache License 2.0
23 stars 17 forks source link

Support global custom error handler #31

Closed corelchen closed 4 years ago

unknwon commented 4 years ago

Thanks for the PR!

Why do you think the existing ErrorHandler interface isn't sufficient?

https://github.com/go-macaron/binding/blob/b926bfb3a36b2d6e195625da7efa759757d3d865/binding.go#L744-L747

corelchen commented 4 years ago

To resolve issue https://github.com/go-macaron/binding/issues/26 that I submitted. This can set a global ErrorHandler, instead of implementing interface binding.ErrorHandler for each model. A simple example usage is like:

binding.CustomErrorHandler = func(ctx *macaron.Context, errs binding.Errors) {
    if len(errs) > 0 {
        ctx.JSON(200, struct {
            Code    int    `json:"code"`
            Message string `json:"message"`
        }{
            Code: 1001,
            Message: "参数错误",
        })
    }
}
unknwon commented 4 years ago

OK make sense, merging!