2

When overriding HTTPErrorHandler, I observe that status code 200 is sent to the user even if I set the response status to a different value:

package main

import (
    "github.com/labstack/echo/v4"
    "net/http"
)

type MyError struct{}

func (m *MyError) Error() string {
    return "boom"
}

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

    e.HTTPErrorHandler = func(err error, context echo.Context) {
        if _, ok := err.(* MyError); ok {
            println("Got MyError")
            context.SetResponse(&echo.Response{Status: http.StatusBadRequest})
        } else {
            println("Got something else")
        }
    }

    e.GET("/1", func(context echo.Context) error {
        return &MyError{}
    })

    e.GET("/2", func(context echo.Context) error {
        return echo.NewHTTPError(http.StatusForbidden, "Invalid permissions ")
    })

    e.Start(":80")
}

In the above example, requests to either /1 or /2 always return 200. If I comment out the override to HTTPErrorHandler, I get back statuses 500 and 403, respectively. So it seems like overriding HTTPErrorHandler changes all statuses to 200.

I'm OK if there's a way to map errors in middleware.

user2233706
  • 6,148
  • 5
  • 44
  • 86
  • I have middleware that authorizes a user and sends back 403. That works fine if I don't override ```HTTPErrorHandler```. – user2233706 Dec 01 '21 at 15:31
  • Take a look at what the [default](https://pkg.go.dev/github.com/labstack/echo/v4#Echo.DefaultHTTPErrorHandler) does to set the status code, you should probably do the same. Either call [`c.NoContent(code)`](https://github.com/labstack/echo/blob/c6f0c667f145b5e5347ba812c9de5a5a4280bac5/echo.go#L398) or, if you also want to send a body with the error status use one of the content writing methods like [`c.JSON`](https://github.com/labstack/echo/blob/c6f0c667f145b5e5347ba812c9de5a5a4280bac5/echo.go#L400). – mkopriva Dec 01 '21 at 19:05
  • That works, but it's not ideal. You have to reset the status code and message for an HTTPError. Furthermore, if you don't catch a type of error, it gets sent back as 200. It would have been better for errors that aren't changed in the function to retain their original error information. – user2233706 Dec 01 '21 at 20:06
  • I'm not sure what you mean by resetting but, for the ones you don't catch, just call the default, e.g. https://go.dev/play/p/hlWghXEF2bX – mkopriva Dec 02 '21 at 03:49

0 Answers0