Skip to main content

❌ Error

Error builds a json response using the err parameter and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/json

func ExampleErrorGet(request there.Request) there.Response {
if 1 != 2 {
return there.Error(status.InternalServerError, errors.New("something went wrong"))
}
return there.Status(status.OK)
}

When this handler gets called, the final rendered result will be

{"error":"something went wrong"}

For optimal performance the use of json.Marshal is avoided and the response body is built directly. With this way, there is no error that could occur.

func Error(code int, err error) Response {
e := err.Error()
var b bytes.Buffer
b.Grow(len(e) + errorJsonLength)
b.Write(errorJsonOpen)
for i := range e {
if e[i] == '"' {
b.WriteString("\\\"")
continue
}
b.WriteByte(e[i])
}
b.Write(errorJsonClose)
return &jsonResponse{code: code, data: b.Bytes()}
}

var (
errorJsonOpen = []byte("{\"error\":\"")
errorJsonClose = []byte("\"}")
)

const errorJsonLength = 14 // the total length of errorJsonOpen + errorJsonClose