influxdb/errors.go

263 lines
5.9 KiB
Go
Raw Normal View History

package influxdb
2018-08-27 17:09:17 +00:00
import (
"context"
2018-08-27 17:09:17 +00:00
"encoding/json"
"errors"
"fmt"
"net/http"
2018-08-27 17:09:17 +00:00
"strings"
)
// Some error code constant, ideally we want define common platform codes here
// projects on use platform's error, should have their own central place like this.
// Any time this set of constants changes, you must also update the swagger for Error.properties.code.enum.
2018-08-27 17:09:17 +00:00
const (
EInternal = "internal error"
ENotFound = "not found"
EConflict = "conflict" // action cannot be performed
EInvalid = "invalid" // validation failed
EUnprocessableEntity = "unprocessable entity" // data type is correct, but out of range
EEmptyValue = "empty value"
EUnavailable = "unavailable"
EForbidden = "forbidden"
ETooManyRequests = "too many requests"
EUnauthorized = "unauthorized"
EMethodNotAllowed = "method not allowed"
2018-08-27 17:09:17 +00:00
)
// Error is the error struct of platform.
//
// Errors may have error codes, human-readable messages,
// and a logical stack trace.
//
// The Code targets automated handlers so that recovery can occur.
// Msg is used by the system operator to help diagnose and fix the problem.
// Op and Err chain errors together in a logical stack trace to
// further help operators.
//
// To create a simple error,
// &Error{
// Code:ENotFound,
// }
// To show where the error happens, add Op.
// &Error{
// Code: ENotFound,
// Op: "bolt.FindUserByID"
// }
// To show an error with a unpredictable value, add the value in Msg.
// &Error{
// Code: EConflict,
// Message: fmt.Sprintf("organization with name %s already exist", aName),
// }
// To show an error wrapped with another error.
// &Error{
// Code:EInternal,
// Err: err,
// }.
type Error struct {
Code string
Msg string
Op string
Err error
2018-08-27 17:09:17 +00:00
}
// NewError returns an instance of an error.
func NewError(options ...func(*Error)) *Error {
err := &Error{}
for _, o := range options {
o(err)
}
return err
}
// WithErrorErr sets the err on the error.
func WithErrorErr(err error) func(*Error) {
return func(e *Error) {
e.Err = err
}
}
// WithErrorCode sets the code on the error.
func WithErrorCode(code string) func(*Error) {
return func(e *Error) {
e.Code = code
}
}
// WithErrorMsg sets the message on the error.
func WithErrorMsg(msg string) func(*Error) {
return func(e *Error) {
e.Msg = msg
}
}
// WithErrorOp sets the message on the error.
func WithErrorOp(op string) func(*Error) {
return func(e *Error) {
e.Op = op
}
}
refactor: http error serialization matches the new error schema (#15196) The http error schema has been changed to simplify the outward facing API. The `op` and `error` attributes have been dropped because they confused people. The `error` attribute will likely be readded in some form in the future, but only as additional context and will not be required or even suggested for the UI to use. Errors are now output differently both when they are serialized to JSON and when they are output as strings. The `op` is no longer used if it is present. It will only appear as an optional attribute if at all. The `message` attribute for an error is always output and it will be the prefix for any nested error. When this is serialized to JSON, the message is automatically flattened so a nested error such as: influxdb.Error{ Msg: errors.New("something bad happened"), Err: io.EOF, } This would be written to the message as: something bad happened: EOF This matches a developers expectations much more easily as most programmers assume that wrapping an error will act as a prefix for the inner error. This is flattened when written out to HTTP in order to make this logic immaterial to a frontend developer. The code is still present and plays an important role in categorizing the error type. On the other hand, the code will not be output as part of the message as it commonly plays a redundant and confusing role when humans read it. The human readable message usually gives more context and a message like with the code acting as a prefix is generally not desired. But, the code plays a very important role in helping to identify categories of errors and so it is very important as part of the return response.
2019-09-19 15:06:47 +00:00
// Error implements the error interface by writing out the recursive messages.
2018-09-12 19:24:17 +00:00
func (e *Error) Error() string {
refactor: http error serialization matches the new error schema (#15196) The http error schema has been changed to simplify the outward facing API. The `op` and `error` attributes have been dropped because they confused people. The `error` attribute will likely be readded in some form in the future, but only as additional context and will not be required or even suggested for the UI to use. Errors are now output differently both when they are serialized to JSON and when they are output as strings. The `op` is no longer used if it is present. It will only appear as an optional attribute if at all. The `message` attribute for an error is always output and it will be the prefix for any nested error. When this is serialized to JSON, the message is automatically flattened so a nested error such as: influxdb.Error{ Msg: errors.New("something bad happened"), Err: io.EOF, } This would be written to the message as: something bad happened: EOF This matches a developers expectations much more easily as most programmers assume that wrapping an error will act as a prefix for the inner error. This is flattened when written out to HTTP in order to make this logic immaterial to a frontend developer. The code is still present and plays an important role in categorizing the error type. On the other hand, the code will not be output as part of the message as it commonly plays a redundant and confusing role when humans read it. The human readable message usually gives more context and a message like with the code acting as a prefix is generally not desired. But, the code plays a very important role in helping to identify categories of errors and so it is very important as part of the return response.
2019-09-19 15:06:47 +00:00
if e.Msg != "" && e.Err != nil {
var b strings.Builder
2018-08-27 17:09:17 +00:00
b.WriteString(e.Msg)
refactor: http error serialization matches the new error schema (#15196) The http error schema has been changed to simplify the outward facing API. The `op` and `error` attributes have been dropped because they confused people. The `error` attribute will likely be readded in some form in the future, but only as additional context and will not be required or even suggested for the UI to use. Errors are now output differently both when they are serialized to JSON and when they are output as strings. The `op` is no longer used if it is present. It will only appear as an optional attribute if at all. The `message` attribute for an error is always output and it will be the prefix for any nested error. When this is serialized to JSON, the message is automatically flattened so a nested error such as: influxdb.Error{ Msg: errors.New("something bad happened"), Err: io.EOF, } This would be written to the message as: something bad happened: EOF This matches a developers expectations much more easily as most programmers assume that wrapping an error will act as a prefix for the inner error. This is flattened when written out to HTTP in order to make this logic immaterial to a frontend developer. The code is still present and plays an important role in categorizing the error type. On the other hand, the code will not be output as part of the message as it commonly plays a redundant and confusing role when humans read it. The human readable message usually gives more context and a message like with the code acting as a prefix is generally not desired. But, the code plays a very important role in helping to identify categories of errors and so it is very important as part of the return response.
2019-09-19 15:06:47 +00:00
b.WriteString(": ")
b.WriteString(e.Err.Error())
return b.String()
} else if e.Msg != "" {
return e.Msg
} else if e.Err != nil {
return e.Err.Error()
2018-08-27 17:09:17 +00:00
}
refactor: http error serialization matches the new error schema (#15196) The http error schema has been changed to simplify the outward facing API. The `op` and `error` attributes have been dropped because they confused people. The `error` attribute will likely be readded in some form in the future, but only as additional context and will not be required or even suggested for the UI to use. Errors are now output differently both when they are serialized to JSON and when they are output as strings. The `op` is no longer used if it is present. It will only appear as an optional attribute if at all. The `message` attribute for an error is always output and it will be the prefix for any nested error. When this is serialized to JSON, the message is automatically flattened so a nested error such as: influxdb.Error{ Msg: errors.New("something bad happened"), Err: io.EOF, } This would be written to the message as: something bad happened: EOF This matches a developers expectations much more easily as most programmers assume that wrapping an error will act as a prefix for the inner error. This is flattened when written out to HTTP in order to make this logic immaterial to a frontend developer. The code is still present and plays an important role in categorizing the error type. On the other hand, the code will not be output as part of the message as it commonly plays a redundant and confusing role when humans read it. The human readable message usually gives more context and a message like with the code acting as a prefix is generally not desired. But, the code plays a very important role in helping to identify categories of errors and so it is very important as part of the return response.
2019-09-19 15:06:47 +00:00
return fmt.Sprintf("<%s>", e.Code)
2018-08-27 17:09:17 +00:00
}
// ErrorCode returns the code of the root error, if available; otherwise returns EINTERNAL.
func ErrorCode(err error) string {
if err == nil {
return ""
}
e, ok := err.(*Error)
if !ok {
return EInternal
}
if e == nil {
return ""
}
if e.Code != "" {
2018-08-27 17:09:17 +00:00
return e.Code
}
if e.Err != nil {
2018-11-07 18:55:52 +00:00
return ErrorCode(e.Err)
2018-08-27 17:09:17 +00:00
}
2018-08-27 17:09:17 +00:00
return EInternal
}
2018-11-07 18:55:52 +00:00
// ErrorOp returns the op of the error, if available; otherwise return empty string.
func ErrorOp(err error) string {
if err == nil {
return ""
}
e, ok := err.(*Error)
if !ok {
return ""
}
if e == nil {
return ""
}
if e.Op != "" {
2018-11-07 18:55:52 +00:00
return e.Op
}
if e.Err != nil {
2018-11-07 18:55:52 +00:00
return ErrorOp(e.Err)
2018-11-07 18:55:52 +00:00
}
2018-11-07 18:55:52 +00:00
return ""
}
2018-08-27 17:09:17 +00:00
// ErrorMessage returns the human-readable message of the error, if available.
// Otherwise returns a generic error message.
func ErrorMessage(err error) string {
if err == nil {
return ""
}
e, ok := err.(*Error)
if !ok {
return "An internal error has occurred."
}
if e == nil {
return ""
}
if e.Msg != "" {
2018-08-27 17:09:17 +00:00
return e.Msg
}
if e.Err != nil {
2018-08-27 17:09:17 +00:00
return ErrorMessage(e.Err)
}
2018-08-27 17:09:17 +00:00
return "An internal error has occurred."
}
// errEncode an JSON encoding helper that is needed to handle the recursive stack of errors.
type errEncode struct {
Code string `json:"code"` // Code is the machine-readable error code.
Msg string `json:"message,omitempty"` // Msg is a human-readable message.
Op string `json:"op,omitempty"` // Op describes the logical code operation during error.
Err interface{} `json:"error,omitempty"` // Err is a stack of additional errors.
2018-08-27 17:09:17 +00:00
}
// MarshalJSON recursively marshals the stack of Err.
func (e *Error) MarshalJSON() (result []byte, err error) {
ee := errEncode{
Code: e.Code,
Msg: e.Msg,
Op: e.Op,
}
if e.Err != nil {
if _, ok := e.Err.(*Error); ok {
_, err := e.Err.(*Error).MarshalJSON()
2018-08-27 17:09:17 +00:00
if err != nil {
return result, err
}
ee.Err = e.Err
2018-08-27 17:09:17 +00:00
} else {
ee.Err = e.Err.Error()
}
}
return json.Marshal(ee)
}
// UnmarshalJSON recursively unmarshals the error stack.
func (e *Error) UnmarshalJSON(b []byte) (err error) {
ee := new(errEncode)
err = json.Unmarshal(b, ee)
e.Code = ee.Code
e.Msg = ee.Msg
e.Op = ee.Op
e.Err = decodeInternalError(ee.Err)
return err
}
func decodeInternalError(target interface{}) error {
if errStr, ok := target.(string); ok {
return errors.New(errStr)
}
if internalErrMap, ok := target.(map[string]interface{}); ok {
internalErr := new(Error)
if code, ok := internalErrMap["code"].(string); ok {
internalErr.Code = code
}
if msg, ok := internalErrMap["message"].(string); ok {
internalErr.Msg = msg
2018-08-27 17:09:17 +00:00
}
if op, ok := internalErrMap["op"].(string); ok {
internalErr.Op = op
}
internalErr.Err = decodeInternalError(internalErrMap["error"])
return internalErr
2018-08-27 17:09:17 +00:00
}
return nil
2018-08-27 17:09:17 +00:00
}
// HTTPErrorHandler is the interface to handle http error.
type HTTPErrorHandler interface {
HandleHTTPError(ctx context.Context, err error, w http.ResponseWriter)
}