http: better error messages

This commit is contained in:
Tigor Hutasuhut 2024-04-24 22:26:04 +07:00
parent e8a027ca12
commit fd29c35b1a
6 changed files with 25 additions and 11 deletions

View file

@ -30,3 +30,11 @@ func FindMessage(err error) string {
return err.Error()
}
func HTTPMessage(err error) (code int, message string) {
code = FindCodeOrDefault(err, 500)
if code >= 500 {
return code, err.Error()
}
return code, FindMessage(err)
}

View file

@ -1,11 +1,11 @@
POST http://localhost:8080/api/v1/devices HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Content-Length: 155
Content-Length: 160
{
"name": "Laptop",
"slug": "laptop",
"name": "Sync Laptop",
"slug": "sync-l",
"resolution_x": 1920,
"resolution_y": 1080,
"nsfw": 1,

View file

@ -1,9 +1,10 @@
PATCH http://localhost:8080/api/v1/devices/1 HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Content-Length: 55
Content-Length: 78
{
"slug": "sync-l",
"aspect_ratio_tolerance": 0.2,
"nsfw": 1
}

View file

@ -48,8 +48,9 @@ func (routes *Routes) APIDeviceCreate(rw http.ResponseWriter, r *http.Request) {
WindowsWallpaperMode: omit.From(body.WindowsWallpaperMode),
})
if err != nil {
rw.WriteHeader(errs.FindCodeOrDefault(err, http.StatusInternalServerError))
_ = json.NewEncoder(rw).Encode(map[string]string{"error": errs.FindMessage(err)})
code, message := errs.HTTPMessage(err)
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": message})
return
}

View file

@ -4,8 +4,10 @@ import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/tigorlazuardi/redmage/api"
"github.com/tigorlazuardi/redmage/pkg/errs"
"github.com/tigorlazuardi/redmage/pkg/log"
)
@ -17,8 +19,9 @@ func (routes *Routes) APIDeviceList(rw http.ResponseWriter, r *http.Request) {
result, err := routes.API.DevicesList(ctx, query)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": err.Error()})
code, message := errs.HTTPMessage(err)
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": message})
return
}
@ -33,7 +36,7 @@ func parseApiDeviceListQueries(req *http.Request) (params api.DevicesListParams)
params.Limit, _ = strconv.ParseInt(req.FormValue("limit"), 10, 64)
params.Q = req.FormValue("q")
params.OrderBy = req.FormValue("order")
params.Sort = req.FormValue("sort")
params.Sort = strings.ToLower(req.FormValue("sort"))
if params.Limit < 1 {
params.Limit = 10

View file

@ -61,8 +61,9 @@ func (routes *Routes) APIDeviceUpdate(rw http.ResponseWriter, r *http.Request) {
WindowsWallpaperMode: omit.FromPtr(body.WindowsWallpaperMode),
})
if err != nil {
rw.WriteHeader(errs.FindCodeOrDefault(err, http.StatusInternalServerError))
_ = json.NewEncoder(rw).Encode(map[string]string{"error": errs.FindMessage(err)})
code, message := errs.HTTPMessage(err)
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": message})
return
}