add WriteError method for acme api

This commit is contained in:
max furman 2021-03-29 23:16:39 -07:00
parent 9aef84b9af
commit 2e0e62bc4c
2 changed files with 35 additions and 8 deletions

View file

@ -3,8 +3,13 @@ package acme
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"net/http"
"os"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/smallstep/certificates/errs"
"github.com/smallstep/certificates/logging"
) )
// ProblemType is the type of the ACME problem. // ProblemType is the type of the ACME problem.
@ -347,3 +352,27 @@ func (e *Error) ToLog() (interface{}, error) {
} }
return string(b), nil return string(b), nil
} }
// WriteError writes to w a JSON representation of the given error.
func WriteError(w http.ResponseWriter, err *Error) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(err.StatusCode())
// Write errors in the response writer
if rl, ok := w.(logging.ResponseLogger); ok {
rl.WithFields(map[string]interface{}{
"error": err.Err,
})
if os.Getenv("STEPDEBUG") == "1" {
if e, ok := err.Err.(errs.StackTracer); ok {
rl.WithFields(map[string]interface{}{
"stack-trace": fmt.Sprintf("%+v", e),
})
}
}
}
if err := json.NewEncoder(w).Encode(err); err != nil {
log.Println(err)
}
}

View file

@ -14,12 +14,14 @@ import (
// WriteError writes to w a JSON representation of the given error. // WriteError writes to w a JSON representation of the given error.
func WriteError(w http.ResponseWriter, err error) { func WriteError(w http.ResponseWriter, err error) {
switch err.(type) { switch k := err.(type) {
case *acme.Error: case *acme.Error:
w.Header().Set("Content-Type", "application/problem+json") acme.WriteError(w, k)
return
default: default:
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
} }
cause := errors.Cause(err) cause := errors.Cause(err)
if sc, ok := err.(errs.StatusCoder); ok { if sc, ok := err.(errs.StatusCoder); ok {
w.WriteHeader(sc.StatusCode()) w.WriteHeader(sc.StatusCode())
@ -33,15 +35,11 @@ func WriteError(w http.ResponseWriter, err error) {
// Write errors in the response writer // Write errors in the response writer
if rl, ok := w.(logging.ResponseLogger); ok { if rl, ok := w.(logging.ResponseLogger); ok {
logErr := err
if u, ok := err.(*acme.Error); ok {
logErr = u.Err
}
rl.WithFields(map[string]interface{}{ rl.WithFields(map[string]interface{}{
"error": logErr, "error": err,
}) })
if os.Getenv("STEPDEBUG") == "1" { if os.Getenv("STEPDEBUG") == "1" {
if e, ok := logErr.(errs.StackTracer); ok { if e, ok := err.(errs.StackTracer); ok {
rl.WithFields(map[string]interface{}{ rl.WithFields(map[string]interface{}{
"stack-trace": fmt.Sprintf("%+v", e), "stack-trace": fmt.Sprintf("%+v", e),
}) })