fiber icon indicating copy to clipboard operation
fiber copied to clipboard

🤗 Custom error handling

Open fabienbellanger opened this issue 6 years ago • 4 comments

Hi

I'm trying to catch a 404 error with the app.Settings.ErrorHandler method to return a JSON response (not Cannot GET /page-not-found as currently), but it seems that only 500 errors works. It works with a 404 error only if I use:

err := fiber.NewError(404, "Not Found")
c.Next(err)

How can I catch and customize all HTTP errors (all in JSON in my case) like with Echo framework (https://echo.labstack.com/guide/error-handling).

A fiber example:

package main

import "github.com/gofiber/fiber"

func main() {
  app := fiber.New()
  app.Settings.ErrorHandler = func(c *fiber.Ctx, err error) {
	code := fiber.StatusInternalServerError

	if e, ok := err.(*fiber.Error); ok {
		code = e.Code
	}

	if code == 500 {
		c.JSON(fiber.Map{
			"code":    code,
			"message": "Internal Server Error",
		})
	} else if code == 404 {
              c.JSON(fiber.Map{
			"code":    code,
			"message": "Resource Not Found",
		})
       }
  }
  ...
}

A working Echo example:

package main

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

func main() {
        e := echo.New()

        e.HTTPErrorHandler = customHTTPErrorHandler

        ...
}

func customHTTPErrorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	if httpError, ok := err.(*echo.HTTPError); ok {
		code = httpError.Code
	}

	msg := goutils.GetHTTPStatusMessage(code)
	if msg == "" {
		msg = "Unknown Error"
	}

	if code > 400 && code < 500 {
		logger.Log(err, logger.MediumLevel, 0)
	} else if code >= 500 && code < 600 {
		logger.Log(err, logger.HightLevel, 0)
	}

	c.JSON(code, map[string]string{"message": msg})
}

Thanks for this great frameword that is Fiber ;)

fabienbellanger avatar Sep 04 '20 11:09 fabienbellanger

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

welcome[bot] avatar Sep 04 '20 11:09 welcome[bot]

Hey @fabienbellanger I don't know weather this will help you :smile:

package main

import (
	"github.com/gofiber/fiber"
)

func main() {
	app := fiber.New()

	app.Get("/", func(ctx *fiber.Ctx) {
		ctx.SendString("Hello 👋")
	})

	// a custom 404 handler at router tail
	app.Use(func(ctx *fiber.Ctx) {
		ctx.Status(404).JSON(fiber.Map{
			"code":    404,
			"message": "Resource Not Found",
		})
	})

	app.Listen("3000")
}

kiyonlin avatar Sep 05 '20 01:09 kiyonlin

@fabienbellanger, 404 Not Found is not an error according to the RFC. It only tells you that the resource you are trying to look for does not exist in that particular location. To modify the 404 response you can use the example @kiyonlin has given 👍

Fenny avatar Sep 05 '20 02:09 Fenny

@kiyonlin and @Fenny, thanks a lot, it is exactly what i need 👍

fabienbellanger avatar Sep 05 '20 08:09 fabienbellanger