Improve http error messages

This commit is contained in:
Tobie Morgan Hitchcock 2016-09-14 22:33:09 +01:00
parent 3db0d79443
commit ff8a2f03a9
2 changed files with 35 additions and 25 deletions

View file

@ -17,44 +17,43 @@ package web
import ( import (
"github.com/abcum/fibre" "github.com/abcum/fibre"
"github.com/abcum/surreal/kvs" "github.com/abcum/surreal/kvs"
"github.com/abcum/surreal/sql"
) )
func errors(err error, c *fibre.Context) { func errors(err error, c *fibre.Context) {
code := 500 var code int
text := err.Error() var text string
var info map[string]interface{}
switch err.(type) { switch e := err.(type) {
default: default:
err = fibre.NewHTTPError(400, text) code = 400
case *kvs.DBError: case *kvs.DBError:
err = fibre.NewHTTPError(503, text) code, text = 503, e.Error()
case *kvs.TXError: case *kvs.TXError:
err = fibre.NewHTTPError(500, text) code, text = 500, e.Error()
case *kvs.KVError: case *kvs.KVError:
err = fibre.NewHTTPError(409, text) code, text = 409, e.Error()
case *kvs.CKError: case *kvs.CKError:
err = fibre.NewHTTPError(403, text) code, text = 403, e.Error()
} case *sql.ParseError:
code, text = 400, e.Error()
if e, ok := err.(*fibre.HTTPError); ok { case *fibre.HTTPError:
code = e.Code() code = e.Code()
text = e.Error()
} }
switch c.Type() { if _, ok := errs[code]; !ok {
default: code = 500
c.Text(code, text)
case "application/json":
info := errs[code]
info["information"] = text
c.JSON(code, info)
case "application/msgpack":
info := errs[code]
info["information"] = text
c.PACK(code, info)
} }
info = errs[code]
if text != "" {
info["information"] = text
}
c.Send(code, info)
} }
var errs = map[int]map[string]interface{}{ var errs = map[int]map[string]interface{}{

View file

@ -17,10 +17,20 @@ package web
import ( import (
"github.com/abcum/fibre" "github.com/abcum/fibre"
"github.com/abcum/surreal/db" "github.com/abcum/surreal/db"
"github.com/abcum/surreal/sql"
) )
func output(c *fibre.Context, res interface{}) error { func output(c *fibre.Context, err error, res []*db.Response) error {
switch ret := res.(*db.Response); ret.Status {
if err != nil {
return fibre.NewHTTPError(500)
}
if len(res) == 0 {
return fibre.NewHTTPError(500)
}
switch ret := res[0]; ret.Status {
case "OK": case "OK":
return c.Send(200, ret.Result) return c.Send(200, ret.Result)
case "ERR_DB": case "ERR_DB":
@ -34,6 +44,7 @@ func output(c *fibre.Context, res interface{}) error {
default: default:
return fibre.NewHTTPError(400) return fibre.NewHTTPError(400)
} }
} }
func routes(s *fibre.Fibre) { func routes(s *fibre.Fibre) {