Skip to content

Commit

Permalink
Merge pull request #9 from percona/PMM-13658-updates-server-error
Browse files Browse the repository at this point in the history
PMM-13658 fix updates error response
  • Loading branch information
idoqo authored Jan 17, 2025
2 parents 8df942a + 71ad5e1 commit a573276
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
6 changes: 4 additions & 2 deletions pkg/api/update/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package update

import (
"errors"
"github.com/containrrr/watchtower/pkg/types"
"io"
"net/http"
"os"
"strings"

log "github.com/sirupsen/logrus"

"github.com/containrrr/watchtower/pkg/types"
)

var (
Expand Down Expand Up @@ -93,7 +94,8 @@ func (handle *Handler) Handle(w http.ResponseWriter, r *http.Request) {

func handleError(w http.ResponseWriter, err error) {
if err != nil {
if errors.Is(err, &types.ValidationError{}) {
var validationErr *types.ValidationError
if errors.As(err, &validationErr) {
log.Warning(err)
w.WriteHeader(http.StatusPreconditionFailed)
w.Write([]byte(err.Error()))
Expand Down
46 changes: 46 additions & 0 deletions pkg/api/update/update_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package update

import (
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/containrrr/watchtower/pkg/types"
)

func TestHandleError(t *testing.T) {
tests := []struct {
name string
error error
expectedStatus int
}{
{
name: "no error returns OK",
error: nil,
expectedStatus: http.StatusOK,
},
{
name: "validation error returns message",
error: types.NewValidationError("no new image available"),
expectedStatus: http.StatusPreconditionFailed,
},
{
name: "generic server error",
error: errors.New("server error"),
expectedStatus: http.StatusInternalServerError,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rr := httptest.NewRecorder()

handleError(rr, tt.error)

if status := rr.Result().StatusCode; status != tt.expectedStatus {
t.Errorf("the handler wrote status code %d, expected: %d", status, tt.expectedStatus)
}
})
}
}

0 comments on commit a573276

Please sign in to comment.