go-ozzo / ozzo-routing

An extremely fast Go (golang) HTTP router that supports regular expression route matching. Comes with full support for building RESTful APIs.
MIT License
453 stars 51 forks source link

Error handling is not conform with OpenAPI standard #53

Closed donutloop closed 6 years ago

donutloop commented 6 years ago

the router sets for each error case a content type "text/plain" but that behavior is to static. Could you introduce a customizable error handler that the user can decide self what kind of content he wants sending to the cunsomer back or you could extending the collection of http errors (JSON, XML, Text, etc) and error matching.

bildschirmfoto 2018-07-10 um 09 53 54

Behavior of content type Type https://tools.ietf.org/search/rfc2616#section-7.2 Entity body https://tools.ietf.org/search/rfc2616#section-7.2.1

qiangxue commented 6 years ago

This is the last resort when errors are not handled. Usually you should have your own error handler installed (as a middleware) so that handleError is never reached.

donutloop commented 6 years ago

A middleware triggers the same behavior, m`I right with that assumption?

bildschirmfoto 2018-07-12 um 12 31 29
qiangxue commented 6 years ago

Your error handler middleware can be something like the following:

func ErrorHandler(c *routing.Context) (err error) {
    defer func() {
        if e := recover(); e != nil {
            // handle panic here
        }

        if err != nil {
            // handle normal error here (e.g. send error in json response)
            c.Abort()  // call Abort() to stop further middleware processing
        }
    }()

    return c.Next()
}
donutloop commented 6 years ago

Done! Thank you for your offered support!