2017-05-23 18:56:10 +00:00
|
|
|
package error
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// errorResponse is a generic response for sending a error.
|
|
|
|
type errorResponse struct {
|
|
|
|
Err string `json:"err,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteErrorResponse writes an error message to the response and logger.
|
|
|
|
func WriteErrorResponse(w http.ResponseWriter, err error, code int, logger *log.Logger) {
|
|
|
|
if logger != nil {
|
|
|
|
logger.Printf("http error: %s (code=%d)", err, code)
|
|
|
|
}
|
|
|
|
|
2018-04-13 14:01:02 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2017-05-23 18:56:10 +00:00
|
|
|
w.WriteHeader(code)
|
|
|
|
json.NewEncoder(w).Encode(&errorResponse{Err: err.Error()})
|
|
|
|
}
|