diff --git a/hub/errs/types.go b/hub/errs/types.go index fbd9cf7..86a8c9e 100644 --- a/hub/errs/types.go +++ b/hub/errs/types.go @@ -17,7 +17,7 @@ func (e *Error) Error() string { var ( ErrUnexpected = Internal.WithMsg("Unexpected internal error.") ErrNotFound = NotFound.WithMsg("Not found.") - ErrAlreadyExists = Conflict.WithMsg("AlreadyExists.") + ErrAlreadyExists = Conflict.WithMsg("Already exists.") // Validation errors. ErrInvalidIP = BadRequest.WithMsg("Invalid IP.") diff --git a/hub/handler.go b/hub/handler.go index 2614621..ec6aa21 100644 --- a/hub/handler.go +++ b/hub/handler.go @@ -1,8 +1,11 @@ package hub import ( + "errors" + "log" "net/http" "vppn/hub/api" + "vppn/hub/errs" "git.crumpington.com/lib/go/webutil" ) @@ -21,7 +24,7 @@ func (app *App) handlePub(pattern string, fn handlerFunc) { } if err := fn(&s, w, r); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + handleError(w, err) } } @@ -68,8 +71,7 @@ func (app *App) handlePeer(pattern string, fn peerHandlerFunc) { r.ParseForm() if err := fn(peer, w, r); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return + handleError(w, err) } } @@ -77,3 +79,13 @@ func (app *App) handlePeer(pattern string, fn peerHandlerFunc) { webutil.WithLogging( wrapped)) } + +func handleError(w http.ResponseWriter, err error) { + var e *errs.Error + if errors.As(err, &e) { + http.Error(w, e.Msg, e.Code) + } else { + log.Printf("Unexpected error: %v", err) + http.Error(w, "Internal server error.", http.StatusInternalServerError) + } +}