Terminate http request via header error code return or JSON response -
how can call multiple error return functions handlefunc?
i have found similar need in link: golang: terminating or aborting http request.
so, in cases, need return error response http error code, below (code taken link above):
http.handlefunc("/", func(w http.responsewriter, r *http.request) { // examine incoming params if !ok { http.error(w, `invalid input params!`, http.statusbadrequest) return } // normal api serving })
however, in cases need return json response web client:
http.handlefunc("/", func(w http.responsewriter, r *http.request) { // examine incoming params if !ok { w.header().set("content-type", "application/json") w.writeheader(http.statusbadrequest) str := `{"result":"","error":"no valide var"}` fmt.fprint(w, str) return } // normal api serving })
question is: want place error handling part in seperate error function , passing type of error want present function parameter/method. don't know, how semantically.
so, in gist:
if isjsonerror { //call http function serve json error } if ishttperror { //call http function serve http error }
how can semantically? sorry in advance, if i'm not being clear. thank you!
p.s.: i've read following blogpost : http://blog.golang.org/error-handling-and-go
there section there called "simplifying repetitive error handling" - , it's cool need simplify multiple repetitive error handling , can't figure out how to.
the custom handler approach (as per blog post)—with func(w http.responsewriter, r *http.request) error
signature way go. return &httperror{err, code}
or &jsonerror{err, code}
, have servehttp
inspect , render appropriately. e.g.
type handler struct { h func(http.responsewriter, *http.request) error } func (h handler) servehttp(w http.responsewriter, r *http.request) { // execute handler function err := h.h(w, r) if err != nil { switch e := err.(type) { case *htmlerror: // render html response, calling e.err , e.code case *jsonerror: // render json response default: // handle other 'generic' errors don't inspect } } } type htmlerror struct { err error code int } func (e *htmlerror) error() string { return e.err.error() } type jsonerror struct { err error code int } func (e *jsonerror) error() string { return e.err.error() } func somehandler(w http.responsewriter, r *http.request) error { // examine incoming params if !ok { // returns enforced here - avoiding subtle bugs return &httperror{errors.new("no good!"), http.statusbadrequest} } }
small plug: wrote blog post ways centralise error handling handlers similar example above.
Comments
Post a Comment