diff --git a/httperrors/errors.go b/httperrors/errors.go new file mode 100644 index 0000000..df42dbe --- /dev/null +++ b/httperrors/errors.go @@ -0,0 +1,41 @@ +package httperrors + +import ( + "net/http" + + "github.com/integration-system/isp-kit/json" +) + +type HttpError struct { + statusCode int + userMessage string + details []interface{} + err error +} + +func New(statusCode int, userMessage string, internalError error) HttpError { + return HttpError{ + statusCode: statusCode, + userMessage: userMessage, + err: internalError, + } +} + +func (e HttpError) Error() string { + return e.err.Error() +} + +func (e HttpError) WriteError(w http.ResponseWriter) error { + w.Header().Set("content-type", "application/json") + w.WriteHeader(e.statusCode) + data := map[string]interface{}{ + "errorCode": http.StatusText(e.statusCode), + "errorMessage": e.userMessage, + "details": e.details, + } + return json.NewEncoder(w).Encode(data) +} + +func (e *HttpError) WithDetails(details ...interface{}) { + e.details = details +}