Merge pull request #79 from unistack-org/errors
errors: fix FromError and errors.Unmarshal
This commit was merged in pull request #79.
	This commit is contained in:
		| @@ -84,9 +84,9 @@ func New(id, detail string, code int32) error { | |||||||
| // Parse tries to parse a JSON string into an error. If that | // Parse tries to parse a JSON string into an error. If that | ||||||
| // fails, it will set the given string as the error detail. | // fails, it will set the given string as the error detail. | ||||||
| func Parse(err string) *Error { | func Parse(err string) *Error { | ||||||
| 	e := new(Error) | 	e := &Error{} | ||||||
| 	errr := json.Unmarshal([]byte(err), e) | 	nerr := json.Unmarshal([]byte(err), e) | ||||||
| 	if errr != nil { | 	if nerr != nil { | ||||||
| 		e.Detail = err | 		e.Detail = err | ||||||
| 	} | 	} | ||||||
| 	return e | 	return e | ||||||
| @@ -283,6 +283,10 @@ func (e *Error) Unmarshal(data []byte) error { | |||||||
| 			return r == ':' | 			return r == ':' | ||||||
| 		}) | 		}) | ||||||
| 		for idx := 0; idx < len(nparts); idx++ { | 		for idx := 0; idx < len(nparts); idx++ { | ||||||
|  | 			if len(nparts[idx+1]) < 3 { | ||||||
|  | 				idx++ | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
| 			switch { | 			switch { | ||||||
| 			case nparts[idx] == `"id"`: | 			case nparts[idx] == `"id"`: | ||||||
| 				e.ID = nparts[idx+1][1 : len(nparts[idx+1])-1] | 				e.ID = nparts[idx+1][1 : len(nparts[idx+1])-1] | ||||||
| @@ -297,6 +301,7 @@ func (e *Error) Unmarshal(data []byte) error { | |||||||
| 				} | 				} | ||||||
| 				e.Code = int32(c) | 				e.Code = int32(c) | ||||||
| 			} | 			} | ||||||
|  | 			idx++ | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| 	return nil | 	return nil | ||||||
|   | |||||||
| @@ -2,10 +2,24 @@ package errors | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	er "errors" | 	er "errors" | ||||||
|  | 	"fmt" | ||||||
| 	"net/http" | 	"net/http" | ||||||
| 	"testing" | 	"testing" | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | func TestEmpty(t *testing.T) { | ||||||
|  | 	msg := "test" | ||||||
|  | 	var err *Error | ||||||
|  | 	err = FromError(fmt.Errorf(msg)) | ||||||
|  | 	if err.Detail != msg { | ||||||
|  | 		t.Fatalf("invalid error %v", err) | ||||||
|  | 	} | ||||||
|  | 	err = FromError(fmt.Errorf(`{"id":"","detail":"%s","status":"%s","code":0}`, msg, msg)) | ||||||
|  | 	if err.Detail != msg || err.Status != msg { | ||||||
|  | 		t.Fatalf("invalid error %#+v", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| func TestFromError(t *testing.T) { | func TestFromError(t *testing.T) { | ||||||
| 	err := NotFound("go.micro.test", "%s", "example") | 	err := NotFound("go.micro.test", "%s", "example") | ||||||
| 	merr := FromError(err) | 	merr := FromError(err) | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user