package apierror import ( "encoding/json" "errors" "fmt" "net/http/httptest" "reflect" "testing" ) func TestError_ErrorString(t *testing.T) { for _, tc := range []struct { e *Error want string }{ {&Error{Message: "x"}, "x"}, {&Error{Message: "x", Cause: errors.New("y")}, "x: y"}, } { if got := tc.e.Error(); got != tc.want { t.Errorf("Error() = %q, want %q", got, tc.want) } } } func TestError_Unwrap(t *testing.T) { cause := errors.New("boom") e := &Error{Message: "x", Cause: cause} if got := e.Unwrap(); got != cause { t.Fatalf("Unwrap() = %v, want %v", got, cause) } e2 := &Error{Message: "x"} if got := e2.Unwrap(); got != nil { t.Fatalf("Unwrap() with nil Cause = %v, want nil", got) } } // From turns any error into the answer a handler writes: nil stays nil, an // *Error (wrapped or not) is kept as it is, and anything else is a 500 that // keeps the error as its cause for the log. func TestFrom(t *testing.T) { if got := From(nil); got != nil { t.Errorf("From(nil) = %v, want nil", got) } orig := NotFound("track") if got := From(orig); got != orig { t.Errorf("From(*Error) = %p, want the same %p", got, orig) } if got := From(fmt.Errorf("ctx: %w", orig)); got != orig { t.Errorf("From(wrapped *Error) = %v, want the *Error it wraps", got) } plain := errors.New("boom") if got := From(plain); got == nil || got.Status != 500 || got.Code != "server_error" || got.Cause != plain { t.Errorf("From(plain) = %+v, want a 500 server_error caused by it", got) } } func TestConstructors_FieldsCorrect(t *testing.T) { tests := []struct { name string err *Error wantStatus int wantCode string wantMessage string }{ { name: "NotFound", err: NotFound("track"), wantStatus: 404, wantCode: "track_not_found", wantMessage: "track not found", }, { name: "BadRequest", err: BadRequest("invalid_input", "invalid input"), wantStatus: 400, wantCode: "invalid_input", wantMessage: "invalid input", }, { name: "Conflict", err: Conflict("already_exists", "already exists"), wantStatus: 409, wantCode: "already_exists", wantMessage: "already exists", }, { name: "Forbidden", err: Forbidden("forbidden", "forbidden"), wantStatus: 403, wantCode: "forbidden", wantMessage: "forbidden", }, { name: "Unauthorized", err: Unauthorized("unauthorized", "authentication required"), wantStatus: 401, wantCode: "unauthorized", wantMessage: "authentication required", }, { name: "Internal", err: Internal(errors.New("boom")), wantStatus: 500, wantCode: "server_error", wantMessage: "internal server error", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.err.Status != tt.wantStatus { t.Errorf("Status = %d, want %d", tt.err.Status, tt.wantStatus) } if tt.err.Code != tt.wantCode { t.Errorf("Code = %q, want %q", tt.err.Code, tt.wantCode) } if tt.err.Message != tt.wantMessage { t.Errorf("Message = %q, want %q", tt.err.Message, tt.wantMessage) } }) } } func TestInternalMsg(t *testing.T) { cause := errors.New("db down") e := InternalMsg("lookup failed", cause) if e.Status != 500 { t.Errorf("Status = %d, want 500", e.Status) } if e.Code != "server_error" { t.Errorf("Code = %q, want server_error", e.Code) } if e.Message != "lookup failed" { t.Errorf("Message = %q, want lookup failed", e.Message) } if !errors.Is(e, cause) { t.Errorf("expected Is(cause) to be true") } } func TestSentinels_Identity(t *testing.T) { wrapped := fmt.Errorf("ctx: %w", ErrNotFound) var apiErr *Error if !errors.As(wrapped, &apiErr) { t.Fatal("errors.As(wrapped, &apiErr) = false, want true") } if apiErr != ErrNotFound { t.Fatalf("recovered error pointer = %p, want %p", apiErr, ErrNotFound) } } // Write sends the status and a JSON body holding exactly the code and the // message. A plain error goes out as a 500 whose message hides its text. func TestWrite_SendsTheEnvelopeAndHidesAPlainErrorsText(t *testing.T) { for _, tc := range []struct { err error status int code, message string }{ {fmt.Errorf("ctx: %w", NotFound("track")), 404, "track_not_found", "track not found"}, {errors.New("boom: secret detail"), 500, "server_error", "internal server error"}, } { rec := httptest.NewRecorder() Write(rec, tc.err) if rec.Code != tc.status { t.Errorf("%v: status = %d, want %d", tc.err, rec.Code, tc.status) } if ct := rec.Header().Get("Content-Type"); ct != "application/json" { t.Errorf("%v: Content-Type = %q, want application/json", tc.err, ct) } var raw map[string]map[string]string if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil { t.Fatalf("%v: body is not the envelope: %v (%s)", tc.err, err, rec.Body.String()) } want := map[string]map[string]string{"error": {"code": tc.code, "message": tc.message}} if !reflect.DeepEqual(raw, want) { t.Errorf("%v: body = %v, want %v", tc.err, raw, want) } } }