contrib icon indicating copy to clipboard operation
contrib copied to clipboard

🚀 [Feature]: expose the underlying FastHTTP upgrade error

Open mickaelvieira opened this issue 1 year ago • 0 comments

Feature Description

Hi everyone,

Debugging websocket connection errors can be quite difficult in some scenarios and I was wondering whether it would be possible to expose the underlying Upgrade error.

I may be wrong but it does not seem to be possible to retrieve the error returned by the FastHTTP Upgrade function as the middleware always returns a ErrUpgradeRequired error.

https://github.com/gofiber/contrib/blob/main/websocket/websocket.go#L132

The idea is to add a new struct to wrap the original error

type UpgradeError struct {
	reason error
}

func (e *UpgradeError) Error() string {
	return fiber.ErrUpgradeRequired.Error()
}

func (e *UpgradeError) Unwrap() error {
	return e.reason
}

// ...

if err := upgrader.Upgrade(c.Context(), func(fconn *websocket.Conn) {
	conn.Conn = fconn
	defer releaseConn(conn)
	handler(conn)
}); err != nil { // Upgrading required
	return &UpgradeError{reason: err}
}

Users can then wrap the middleware with their own error handler

handleErrors(websocket.New(func(c *websocket.Conn) {})
func handleErrors(handler fiber.Handler) fiber.Handler {
	return func(c *fiber.Ctx) error {
		err := handler(c)

		var upgradeError *UpgradeError
		if errors.As(err, &upgradeError ) {
			lg.Println(upgradeError.Unwrap())
		}
		return err
	}
}

Hopefully my explanation makes sense. I'm happy to submit a pull request if you find this useful.

Thanks for the great work on fiber!

Additional Context (optional)

No response

Code Snippet (optional)

package main

import "github.com/gofiber/contrib/%package%"

func main() {
  // Steps to reproduce
}

Checklist:

  • [X] I agree to follow Fiber's Code of Conduct.
  • [X] I have checked for existing issues that describe my suggestion prior to opening this one.
  • [X] I understand that improperly formatted feature requests may be closed without explanation.

mickaelvieira avatar Jun 17 '23 09:06 mickaelvieira