Skip to content

🐛 [Bug]: Custom ErrorHandler is not always called #3906

@duhnnie

Description

@duhnnie

Bug Description

Configured custom ErrorHandler for a sub app is not always called resulting in a different response randomly.

How to Reproduce

  1. Configure a custom ErrorHandler for a sub app, create some endpoints for that sub app that always returns an error, so is expected ErrorHandler to be called always, but it's not called always.

    Or use the code in the Code Snippet section below

    Or clone this repo created exclusively for this issue: https://github.com/duhnnie/Fiber-bug-repo

  2. Run the code, then make a request to GET api/v1/users many times, you'll see that sometimes the response format changes, sometimes the custom ErrorHandler is used, some others the default one is used.

Expected Behavior

Since a custom ErrorHandler is configured for the sub app at api/v1/users, all calls to GET api/v1/users should use it, resulting always in a response like the following:

{
  "code": 400,
  "errorHandler": "defaultErrorHandler",
  "message": "some error occurred"
}

Fiber Version

2.52.10

Code Snippet (optional)

package main

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gofiber/fiber/v2"
)

func DefaultErrorHandler(c *fiber.Ctx, err error) error {
	code := http.StatusBadRequest
	res := map[string]any{
		"code":         code,
		"errorHandler": "defaultErrorHandler",
		"message":      err.Error(),
	}

	// Send a custom error response
	return c.Status(code).JSON(res)
}

func getUser(c *fiber.Ctx) error {
	// It always fails
	return errors.New("some error occurred")
}

func userRoutes() *fiber.App {
	app := fiber.New()
	app.Get("/", getUser)

	return app
}

func V1Routes() *fiber.App {
	app := fiber.New(fiber.Config{
		ErrorHandler: DefaultErrorHandler,
	})

	app.Mount("/users", userRoutes())
	return app
}

func main() {
	port := 8080
	app := fiber.New()
	app.Mount("/api/v1", V1Routes())

	fmt.Printf("running on port %d...\n", port)

	err := app.Listen(fmt.Sprintf(":%d", port))
	if err != nil {
		panic(err)
	}

	// curl http://localhost:8080/api/v1/users
}

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions