Map error to HTTP status code in Labstack Echo

Viewed 576

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.

0 Answers
Related