Skip to content

echo.context.cjson should encode the JSON before writing the status code #1334

Closed
@noamt

Description

@noamt

Issue Description

echo.context.cjson first writes the status code header (200) and then encodes the JSON body.

When there's an error during encoding, the error is returned and may be handled but the status code is already set.
This results in users getting the response body of the handled error but the status code of 200.

Checklist

  • [ X ] Dependencies installed
  • [ X ] No typos
  • [ X ] Searched existing issues and docs

Expected behaviour

An error handler should be able to rewrite the status code after an encoding error.

Actual behaviour

A status code is written before the error handler gets a chance to act and the user receives an error message with a success status code.

Steps to reproduce

Run the code below and make a request like:

curl -v localhost:1337/something

The response status is 200 OK while the body is {"error":"internal server error"}

Working code to debug

package main
import (
	"github.com/labstack/echo/v4"
	"log"
	"math"
	"net/http"
)

func main() {
	e := echo.New()
	e.HTTPErrorHandler = func(err error, c echo.Context) {
		c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal server error"})
	}
	e.GET("/something", func(context echo.Context) error {
		return context.JSON(http.StatusOK, map[string]interface{}{
			"result": math.NaN(),
		})
	})
	if err := e.Start(":1337"); err != nil {
		log.Println("shutting down the server")
	}
}

Version/commit

4.1.5

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions