marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body. If serialization fails, it will use a descriptive Internal error instead.
(twerr twirp.Error)
| 721 | // marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body. |
| 722 | // If serialization fails, it will use a descriptive Internal error instead. |
| 723 | func marshalErrorToJSON(twerr twirp.Error) []byte { |
| 724 | // make sure that msg is not too large |
| 725 | msg := twerr.Msg() |
| 726 | if len(msg) > 1e6 { |
| 727 | msg = msg[:1e6] |
| 728 | } |
| 729 | |
| 730 | tj := twerrJSON{ |
| 731 | Code: string(twerr.Code()), |
| 732 | Msg: msg, |
| 733 | Meta: twerr.MetaMap(), |
| 734 | } |
| 735 | |
| 736 | buf, err := json.Marshal(&tj) |
| 737 | if err != nil { |
| 738 | buf = []byte("{\"type\": \"" + twirp.Internal + "\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback |
| 739 | } |
| 740 | |
| 741 | return buf |
| 742 | } |
| 743 | |
| 744 | // errorFromResponse builds a twirp.Error from a non-200 HTTP response. |
| 745 | // If the response has a valid serialized Twirp error, then it's returned. |
no test coverage detected