Skip to content

Commit

Permalink
Improve HTTP error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
nevillelyh committed Dec 12, 2024
1 parent 99d5991 commit 6cdac12
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
5 changes: 4 additions & 1 deletion internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import (
)

var (
ErrNotFound = errors.New("prediction ID not found")
ErrExists = errors.New("prediction exists")
ErrNotFound = errors.New("prediction not found")
ErrDefunct = errors.New("server is defunct")
ErrSetupFailed = errors.New("setup failed")
)

func NewServer(addr string, runner *Runner) *http.Server {
Expand Down
8 changes: 4 additions & 4 deletions internal/server/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,19 +192,19 @@ func (r *Runner) predict(req PredictionRequest) (chan PredictionResponse, error)
log := logger.Sugar()
if r.status == StatusSetupFailed {
log.Errorw("prediction rejected: setup failed")
return nil, fmt.Errorf("setup failed")
return nil, ErrSetupFailed
} else if r.status == StatusDefunct {
log.Errorw("prediction rejected: server is defunct")
return nil, fmt.Errorf("server is defunct")
return nil, ErrDefunct
}
if req.CreatedAt == "" {
req.CreatedAt = util.NowIso()
}
r.mu.Lock()
if _, ok := r.pending[req.Id]; ok {
r.mu.Unlock()
log.Errorw("prediction rejected: prediction ID exists", "id", req.Id)
return nil, fmt.Errorf("prediction ID exists")
log.Errorw("prediction rejected: prediction exists", "id", req.Id)
return nil, ErrExists
}
r.mu.Unlock()

Expand Down
13 changes: 12 additions & 1 deletion internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,20 @@ func (h *Handler) Predict(w http.ResponseWriter, r *http.Request) {
}

c, err := h.runner.predict(req)
if err != nil {
if errors.Is(err, ErrDefunct) {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
} else if errors.Is(err, ErrExists) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
} else if errors.Is(err, ErrSetupFailed) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

if c == nil {
w.WriteHeader(http.StatusAccepted)
resp := PredictionResponse{Id: req.Id, Status: "starting"}
Expand Down

0 comments on commit 6cdac12

Please sign in to comment.