Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds WriteError func for writing Twirp errors to http.ResponseWriter #192

Merged
merged 2 commits into from Nov 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/errors.md
Expand Up @@ -121,3 +121,24 @@ If your service requires errors with complex metadata, you should consider addin
wrappers on top of the auto-generated clients, or just include business-logic errors as
part of the Protobuf messages (add an error field to proto messages).

### Writing HTTP Errors outside Twirp services

Twirp services can be [muxed with other HTTP services](mux.md). For consistent responses
and error codes _outside_ Twirp servers, such as http middlewares, you can call `twirp.WriteError`.

The error is expected to satisfy a `twirp.Error`, otherwise it is wrapped with `twirp.InternalError`.

Usage:

```go
rpc.WriteError(w, twirp.NewError(twirp.Unauthenticated, "invalid token"))
```

To simplify `twirp.Error` composition, a few constructors are available, such as `NotFoundError`
and `RequiredArgumentError`. See [docs](https://godoc.org/github.com/twitchtv/twirp#Error).

With constructor:

```go
rpc.WriteError(w, twirp.RequiredArgumentError("user_id"))
```
74 changes: 73 additions & 1 deletion errors.go
Expand Up @@ -41,7 +41,12 @@
//
package twirp

import "fmt"
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)

// Error represents an error in a Twirp service call.
type Error interface {
Expand Down Expand Up @@ -346,3 +351,70 @@ func (e *wrappedErr) WithMeta(key string, val string) Error {
}
}
func (e *wrappedErr) Cause() error { return e.cause }

// WriteError writes an HTTP response with a valid Twirp error format (code, msg, meta).
// Useful outside of the Twirp server (e.g. http middleware).
// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err)
func WriteError(resp http.ResponseWriter, err error) {
writeError(resp, err)
}

// writeError writes Twirp errors in the response.
func writeError(resp http.ResponseWriter, err error) {
// Non-twirp errors are wrapped as Internal (default)
twerr, ok := err.(Error)
if !ok {
twerr = InternalErrorWith(err)
}

statusCode := ServerHTTPStatusFromErrorCode(twerr.Code())
respBody := marshalErrorToJSON(twerr)

resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON
resp.Header().Set("Content-Length", strconv.Itoa(len(respBody)))
resp.WriteHeader(statusCode) // set HTTP status code and send response

_, writeErr := resp.Write(respBody)
if writeErr != nil {
// We have two options here. We could log the error, or just silently
// ignore the error.
//
// Logging is unacceptable because we don't have a user-controlled
// logger; writing out to stderr without permission is too rude.
//
// Silently ignoring the error is our least-bad option. It's highly
// likely that the connection is broken and the original 'err' says
// so anyway.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or return the error to the caller and let them log/ignore?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! You're completely right that this is a very different situation from the generated code. This should most certainly be able to return an error.

It's unfortunate that this would be a breaking change and require a major version bump. This is why public API is hard. Ouch.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed this could return an error, and probably should within this pkg.

But on the flip-side, it would no longer be a drop-in replacement to the generated version of WriteError.

In our case we were importing stub packages in various places outside the twirp stack, so it made sense to have it this way.

But it wouldn't be too hard to refactor with the returned error (we'd probably drop it anyways).

Maybe in a v6 we could add a returned error, or in v5 add a new function that returns the underlying error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would technically break the public API, but would not do so in a code-breaking way.

Since this function doesn't return anything, all existing code would look like

twirp.WriteError(resp, err)

This would not break if you started returning errors. i.e. you can get away with adding it in a minor version.

If that feels too close to the edge of the dark side.

v5 add a new function that returns the underlying error.

💯
I do not claim to know how to cleanly fix a public API. Probably something like this work?

  • Add another method to return error
  • Mark the current one deprecated
  • In V6, drop the current method

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this discussion - let's move it to an issue though, since I don't think anybody else is seeing this :) @ofpiyush, can you make an issue?

_ = writeErr
}
}

// JSON serialization for errors
type twerrJSON struct {
Code string `json:"code"`
Msg string `json:"msg"`
Meta map[string]string `json:"meta,omitempty"`
}

// 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.
func marshalErrorToJSON(twerr Error) []byte {
// make sure that msg is not too large
msg := twerr.Msg()
if len(msg) > 1e6 {
msg = msg[:1e6]
}

tj := twerrJSON{
Code: string(twerr.Code()),
Msg: msg,
Meta: twerr.MetaMap(),
}

buf, err := json.Marshal(&tj)
if err != nil {
buf = []byte("{\"type\": \"" + Internal + "\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback
}

return buf
}