Created
March 1, 2019 20:35
-
-
Save vtolstov/968592741804e6fa2421a4d040c6371e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package errors | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/micro/go-micro/errors" | |
) | |
func unwrap(merr *errors.Error) *errors.Error { | |
var derr *errors.Error | |
if err := json.Unmarshal([]byte(merr.Detail), &derr); err != nil { | |
return merr | |
} | |
return unwrap(derr) | |
} | |
func WriteJson(w http.ResponseWriter, merr error) error { | |
var err error | |
var rsp *errors.Error | |
w.Header().Set("Content-Type", "application/json") | |
switch v := merr.(type) { | |
case *errors.Error: | |
rsp = unwrap(merr.(*errors.Error)) | |
default: | |
// fmt.Printf("%T %#+v\n", merr, merr) | |
err = json.Unmarshal([]byte(merr.Error()), &rsp) | |
if err != nil { | |
rsp = &errors.Error{ | |
Id: "org.unistack.api", | |
Code: http.StatusInternalServerError, | |
Detail: fmt.Sprintf("%v", v), | |
Status: http.StatusText(http.StatusInternalServerError), | |
} | |
} | |
} | |
w.WriteHeader(int(rsp.Code)) | |
_, err = w.Write([]byte(rsp.Error())) | |
log.Println(rsp.Error()) | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment