Skip to content

Commit

Permalink
added error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
kevkevinpal committed Dec 11, 2024
1 parent 06ddfe4 commit def51f8
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
3 changes: 1 addition & 2 deletions handlers/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ func TestGetAdminPubkeys(t *testing.T) {

handler.ServeHTTP(rr, req)

t.Errorf("handler returned wrong status code: got TEST want TEST")
if status := rr.Code; status != rr.Code {
if status := rr.Code; status != rr.Status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
Expand Down
3 changes: 3 additions & 0 deletions routes/ticket_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import (
"github.com/stakwork/sphinx-tribes/auth"
"github.com/stakwork/sphinx-tribes/db"
"github.com/stakwork/sphinx-tribes/handlers"
"github.com/stakwork/sphinx-tribes/utils"
)

func TicketRoutes() chi.Router {
r := chi.NewRouter()
ticketHandler := handlers.NewTicketHandler(http.DefaultClient, db.DB)

r.Use(utils.ErrorHandler)

r.Group(func(r chi.Router) {
r.Get("/{uuid}", ticketHandler.GetTicket)
r.Post("/review", ticketHandler.ProcessTicketReview)
Expand Down
53 changes: 53 additions & 0 deletions utils/error_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package utils

import (
"database/sql"
"encoding/json"
"errors"
"fmt"

"net/http"
)

type customError struct {
error
StatusCode int
}

func ErrorHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
# Add logic here to then send to jarvis with the correct values
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()

ww := &responseWriterWrapper{ResponseWriter: w}
next.ServeHTTP(ww, r)

if ww.error != nil {
statusCode := http.StatusInternalServerError
if errors.Is(ww.error, sql.ErrNoRows) {
statusCode = http.StatusNotFound
} else if err, ok := ww.error.(*customError); ok {
statusCode = err.StatusCode
}

w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(map[string]string{"error": ww.error.Error()})
}
})
}

type responseWriterWrapper struct {
http.ResponseWriter
error error
}

func (w *responseWriterWrapper) WriteHeader(statusCode int) {
if statusCode >= http.StatusBadRequest {
w.error = fmt.Errorf("HTTP %d: %s", statusCode, http.StatusText(statusCode))
}
w.ResponseWriter.WriteHeader(statusCode)
}

0 comments on commit def51f8

Please sign in to comment.