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"
|
2021-05-03 19:48:20 +00:00
|
|
|
"github.com/smallstep/certificates/authority/admin"
|
2019-12-16 07:54:25 +00:00
|
|
|
"github.com/smallstep/certificates/errs"
|
2018-11-01 04:36:01 +00:00
|
|
|
"github.com/smallstep/certificates/logging"
|
2021-02-26 23:34:50 +00:00
|
|
|
"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) {
|
2021-03-30 06:16:39 +00:00
|
|
|
switch k := err.(type) {
|
2019-05-27 00:41:10 +00:00
|
|
|
case *acme.Error:
|
2021-03-30 06:16:39 +00:00
|
|
|
acme.WriteError(w, k)
|
|
|
|
return
|
2021-05-03 19:48:20 +00:00
|
|
|
case *admin.Error:
|
|
|
|
admin.WriteError(w, k)
|
2021-05-18 04:07:25 +00:00
|
|
|
return
|
2021-02-26 23:34:50 +00:00
|
|
|
case *scep.Error:
|
|
|
|
w.Header().Set("Content-Type", "text/plain")
|
2019-05-27 00:41:10 +00:00
|
|
|
default:
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
}
|
2021-03-30 06:16:39 +00:00
|
|
|
|
2018-10-05 21:48:36 +00:00
|
|
|
cause := errors.Cause(err)
|
2019-12-16 07:54:25 +00:00
|
|
|
if sc, ok := err.(errs.StatusCoder); ok {
|
2018-10-05 21:48:36 +00:00
|
|
|
w.WriteHeader(sc.StatusCode())
|
|
|
|
} else {
|
2019-12-16 07:54:25 +00:00
|
|
|
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{}{
|
2021-03-30 06:16:39 +00:00
|
|
|
"error": err,
|
2018-10-05 21:48:36 +00:00
|
|
|
})
|
|
|
|
if os.Getenv("STEPDEBUG") == "1" {
|
2021-03-30 06:16:39 +00:00
|
|
|
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),
|
|
|
|
})
|
2021-10-08 18:59:57 +00:00
|
|
|
} else if e, ok := cause.(errs.StackTracer); ok {
|
|
|
|
rl.WithFields(map[string]interface{}{
|
|
|
|
"stack-trace": fmt.Sprintf("%+v", e),
|
|
|
|
})
|
2018-10-05 21:48:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.NewEncoder(w).Encode(err); err != nil {
|
|
|
|
LogError(w, err)
|
|
|
|
}
|
|
|
|
}
|