Explorar el Código

add WriteError method for acme api

max furman hace 5 años
padre
commit
2e0e62bc4c
Se han modificado 2 ficheros con 35 adiciones y 8 borrados
  1. 29 0
      acme/errors.go
  2. 6 8
      api/errors.go

+ 29 - 0
acme/errors.go

@@ -3,8 +3,13 @@ package acme
 import (
 	"encoding/json"
 	"fmt"
+	"log"
+	"net/http"
+	"os"
 
 	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/errs"
+	"github.com/smallstep/certificates/logging"
 )
 
 // ProblemType is the type of the ACME problem.
@@ -347,3 +352,27 @@ func (e *Error) ToLog() (interface{}, error) {
 	}
 	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)
+	}
+}

+ 6 - 8
api/errors.go

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