certificates/api/errors.go

63 lines
1.5 KiB
Go
Raw Normal View History

2018-10-05 21:48:36 +00:00
package api
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/pkg/errors"
2019-05-27 00:41:10 +00:00
"github.com/smallstep/certificates/acme"
"github.com/smallstep/certificates/errs"
"github.com/smallstep/certificates/logging"
"github.com/smallstep/certificates/scep"
2018-10-05 21:48:36 +00:00
)
// WriteError writes to w a JSON representation of the given error.
func WriteError(w http.ResponseWriter, err error) {
2019-05-27 00:41:10 +00:00
switch k := err.(type) {
case *acme.Error:
w.Header().Set("Content-Type", "application/problem+json")
err = k.ToACME()
case *scep.Error:
// TODO: check if this is correct; and should we do some more processing?
w.Header().Set("Content-Type", "text/plain")
2019-05-27 00:41:10 +00:00
default:
w.Header().Set("Content-Type", "application/json")
}
2018-10-05 21:48:36 +00:00
cause := errors.Cause(err)
if sc, ok := err.(errs.StatusCoder); ok {
2018-10-05 21:48:36 +00:00
w.WriteHeader(sc.StatusCode())
} else {
if sc, ok := cause.(errs.StatusCoder); ok {
2018-10-05 21:48:36 +00:00
w.WriteHeader(sc.StatusCode())
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
// Write errors in the response writer
if rl, ok := w.(logging.ResponseLogger); ok {
rl.WithFields(map[string]interface{}{
"error": err,
})
if os.Getenv("STEPDEBUG") == "1" {
if e, ok := err.(errs.StackTracer); ok {
2018-10-05 21:48:36 +00:00
rl.WithFields(map[string]interface{}{
"stack-trace": fmt.Sprintf("%+v", e),
})
} else {
if e, ok := cause.(errs.StackTracer); ok {
2018-10-05 21:48:36 +00:00
rl.WithFields(map[string]interface{}{
"stack-trace": fmt.Sprintf("%+v", e),
})
}
}
}
}
if err := json.NewEncoder(w).Encode(err); err != nil {
LogError(w, err)
}
}