go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

How to return error properly? #5

Closed kolkov closed 8 years ago

kolkov commented 8 years ago

How to return correct http status error from validation error?

func SaveHandler(cPtr *routing.Context) error {
    var actor models.Actor
    cPtr.Read(&actor)
    err := actor.Validate()
    if err != nil {
        return err
    }
    return actor.Save()
}
...

func (m *Actor) Save() error {
    err := db.Model(m).Insert()
    if err != nil {
        fmt.Println("Exec err:", err.Error())
    }
    return err
}

Return http 500, and error in json. Is it correct?

qiangxue commented 8 years ago

For validation errors, the correct status code should be 400.

I suppose you are using ozzo-routing. You may use the fault.Recovery() middleware and set your own error handler. In the error handler, you should check the type of the error. If you see validation.Errors, you should set the status code as 400.

kolkov commented 8 years ago

Thanks! Can you give me some example for ozzo-routing, please!

qiangxue commented 8 years ago

I'm creating a restful app boilerplate in Go and will publish it possibly next week.

kolkov commented 8 years ago

Thanks! I want to create some more complex application example in ozzo with backend and frontend with Angular.