Skip to content

Commit

Permalink
BREAKING: WithErrorHandler server option to engine option
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanhitt committed Dec 29, 2024
1 parent dabef5f commit 97e2168
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 5 deletions.
11 changes: 11 additions & 0 deletions engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ func WithOpenAPIConfig(config OpenAPIConfig) func(*Engine) {
}
}

// WithErrorHandler sets a customer error handler for the server
func WithErrorHandler(errorHandler func(err error) error) func(*Engine) {
return func(e *Engine) {
if errorHandler == nil {
panic("errorHandler cannot be nil")
}

e.ErrorHandler = errorHandler
}
}

// OutputOpenAPISpec takes the OpenAPI spec and outputs it to a JSON file
func (e *Engine) OutputOpenAPISpec() []byte {
e.OpenAPI.computeTags()
Expand Down
40 changes: 40 additions & 0 deletions engine_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package fuego

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestWithErrorHandler(t *testing.T) {
t.Run("default engine", func(t *testing.T) {
e := NewEngine()
err := NotFoundError{
Err: errors.New("Not Found :c"),
}
errResponse := e.ErrorHandler(err)
require.ErrorAs(t, errResponse, &HTTPError{})
})
t.Run("custom handler", func(t *testing.T) {
e := NewEngine(
WithErrorHandler(func(err error) error {
return fmt.Errorf("%w foobar", err)
}),
)
err := NotFoundError{
Err: errors.New("Not Found :c"),
}
errResponse := e.ErrorHandler(err)
require.ErrorAs(t, errResponse, &HTTPError{})
require.ErrorContains(t, errResponse, "Not Found :c foobar")
})
t.Run("should be fatal", func(t *testing.T) {
require.Panics(t, func() {
NewEngine(
WithErrorHandler(nil),
)
})
})
}
5 changes: 0 additions & 5 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,6 @@ func WithErrorSerializer(serializer ErrorSender) func(*Server) {
return func(c *Server) { c.SerializeError = serializer }
}

// WithErrorHandler sets a customer error handler for the server
func WithErrorHandler(errorHandler func(err error) error) func(*Server) {
return func(c *Server) { c.ErrorHandler = errorHandler }
}

// WithoutStartupMessages disables the startup message
func WithoutStartupMessages() func(*Server) {
return func(c *Server) {
Expand Down

0 comments on commit 97e2168

Please sign in to comment.