Skip to content

🔥 feat: Add support for NewErrorf #3463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,16 +881,29 @@
return e.Message
}

// NewError creates a new Error instance with an optional message
func NewError(code int, message ...string) *Error {
err := &Error{
Code: code,
Message: utils.StatusMessage(code),
}
if len(message) > 0 {
err.Message = message[0]
// NewError creates a new Error instance with an optional message.
// Additional arguments are formatted using fmt.Sprintf when provided.
// If the first argument in the message slice is not a string, the function
// falls back to using fmt.Sprint on the first element to generate the message.
func NewError(code int, message ...any) *Error {
switch len(message) {
case 0:
// nothing to override
case 1:
// One argument → treat it like fmt.Sprint(arg)
msg = fmt.Sprint(message[0])

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, ubuntu-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, macos-latest)

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / govulncheck-check

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / lint

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / repeated

undefined: msg

Check failure on line 894 in app.go

View workflow job for this annotation

GitHub Actions / Compare

undefined: msg
default:
// Two or more → first must be a format string.
if format, ok := message[0].(string); ok {
msg = fmt.Sprintf(format, message[1:]...)

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, ubuntu-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, macos-latest)

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / govulncheck-check

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / lint

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / repeated

undefined: msg

Check failure on line 898 in app.go

View workflow job for this annotation

GitHub Actions / Compare

undefined: msg
} else {
// If the first arg isn’t a string, fall back gracefully
// instead of panicking on the type assertion.
msg = fmt.Sprint(message[0])

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, ubuntu-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, ubuntu-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.23.x, macos-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / unit (1.24.x, macos-latest)

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / govulncheck-check

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / lint

undefined: msg (typecheck)

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / repeated

undefined: msg

Check failure on line 902 in app.go

View workflow job for this annotation

GitHub Actions / Compare

undefined: msg
}
}
return err

return &Error{Code: code, Message: utils.StatusMessage(code)}
}

// Config returns the app config as value ( read-only ).
Expand Down
66 changes: 66 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,72 @@ func Test_NewError(t *testing.T) {
require.Equal(t, "permission denied", e.Message)
}

// go test -run Test_NewError_Format
func Test_NewError_Format(t *testing.T) {
t.Parallel()

type args []any

tests := []struct { //nolint:govet // fieldalignment: this struct is already optimally ordered
name string
want string
code int
in args
}{
{
name: "no-args → default text",
code: StatusNotFound,
in: nil,
want: utils.StatusMessage(StatusNotFound),
},
{
name: "single-string arg overrides",
code: StatusBadRequest,
in: args{"custom bad request"},
want: "custom bad request",
},
{
name: "single non-string arg stringified",
code: StatusInternalServerError,
in: args{errors.New("db down")},
want: "db down",
},
{
name: "single nil interface",
code: StatusInternalServerError,
in: args{any(nil)},
want: "<nil>",
},
{
name: "format string + args",
code: StatusBadRequest,
in: args{"invalid id %d", 10},
want: "invalid id 10",
},
{
name: "format string + excess args",
code: StatusBadRequest,
in: args{"odd %d", 1, 2, 3},
want: "odd 1%!(EXTRA int=2, int=3)",
},
{
name: "≥2 args but first not string",
code: StatusBadRequest,
in: args{errors.New("boom"), 42},
want: "boom",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
e := NewError(tt.code, tt.in...)
require.Equal(t, tt.code, e.Code)
require.Equal(t, tt.want, e.Message)
})
}
}

// go test -run Test_Test_Timeout
func Test_Test_Timeout(t *testing.T) {
t.Parallel()
Expand Down
2 changes: 1 addition & 1 deletion ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1652,7 +1652,7 @@ func (c *DefaultCtx) SendFile(file string, config ...SendFile) error {

// Check for error
if status != StatusNotFound && fsStatus == StatusNotFound {
return NewError(StatusNotFound, fmt.Sprintf("sendfile: file %s not found", filename))
return NewError(StatusNotFound, "sendfile: file %s not found", filename)
}

// Set the status code set by the user if it is different from the fasthttp status code and 200
Expand Down
4 changes: 2 additions & 2 deletions docs/api/fiber.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,12 @@ func (app *App) ShutdownWithContext(ctx context.Context) error
NewError creates a new HTTPError instance with an optional message.

```go title="Signature"
func NewError(code int, message ...string) *Error
func NewError(code int, message ...any) *Error
```

```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
return fiber.NewError(782, "Custom error message")
return fiber.NewError(782, "Custom error %s", "message")
})
```

Expand Down
2 changes: 1 addition & 1 deletion docs/guide/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ app.Get("/", func(c fiber.Ctx) error {
return fiber.ErrServiceUnavailable

// 503 On vacation!
return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
return fiber.NewError(fiber.StatusServiceUnavailable, "On %s", "vacation!")
})
```

Expand Down
Loading