|
| 1 | +package crud |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | +) |
| 7 | + |
| 8 | +// CrudError describes CRUD error object. |
| 9 | +type CrudError struct { |
| 10 | + // ClassName is an error class that implies its source (for example, "CountError"). |
| 11 | + ClassName string |
| 12 | + // Err is the text of reason. |
| 13 | + Err string |
| 14 | + // File is a source code file where the error was caught. |
| 15 | + File string |
| 16 | + // Line is a number of line in the source code file where the error was caught. |
| 17 | + Line uint64 |
| 18 | + // Stack is an information about the call stack when an error |
| 19 | + // occurs in a string format. |
| 20 | + Stack string |
| 21 | + // Str is the text of reason with error class. |
| 22 | + Str string |
| 23 | +} |
| 24 | + |
| 25 | +// NewCrudError creates new CRUD error. |
| 26 | +func NewCrudError(rawErr interface{}) (*CrudError, error) { |
| 27 | + var ( |
| 28 | + mapErr map[interface{}]interface{} |
| 29 | + ok bool |
| 30 | + ) |
| 31 | + |
| 32 | + crudErr := CrudError{} |
| 33 | + |
| 34 | + if mapErr, ok = rawErr.(map[interface{}]interface{}); !ok { |
| 35 | + return nil, errors.New(fmt.Sprintf("Unexpected CRUD error format: %#v", rawErr)) |
| 36 | + } |
| 37 | + |
| 38 | + if value, ok := mapErr["class_name"]; ok { |
| 39 | + if className, ok := value.(string); ok { |
| 40 | + crudErr.ClassName = className |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + if value, ok := mapErr["err"]; ok { |
| 45 | + if err, ok := value.(string); ok { |
| 46 | + crudErr.Err = err |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if value, ok := mapErr["file"]; ok { |
| 51 | + if file, ok := value.(string); ok { |
| 52 | + crudErr.File = file |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if value, ok := mapErr["line"]; ok { |
| 57 | + if line, ok := value.(uint64); ok { |
| 58 | + crudErr.Line = line |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if value, ok := mapErr["stack"]; ok { |
| 63 | + if stack, ok := value.(string); ok { |
| 64 | + crudErr.Stack = stack |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + if value, ok := mapErr["str"]; ok { |
| 69 | + if str, ok := value.(string); ok { |
| 70 | + crudErr.Str = str |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return &crudErr, nil |
| 75 | +} |
| 76 | + |
| 77 | +// Error converts an CrudError to a string. |
| 78 | +func (err CrudError) Error() string { |
| 79 | + return err.Str |
| 80 | +} |
0 commit comments