creachadair / jrpc2

A Go implementation of a JSON-RPC 2.0 server and client.
BSD 3-Clause "New" or "Revised" License
62 stars 10 forks source link

feat: expose function for building error responses #87

Closed brianmcgee closed 1 year ago

brianmcgee commented 1 year ago

I'm building a proxy and have hit an edge case where I need to construct and return a jrpc2.Response with an error:

reqs, err := jrpc2.ParseRequests(data)
if err != nil {
    // return a -32700 Parse Error
    ...
}

Since all the fields of jrpc2.Response are package private I've added a small utility function.

creachadair commented 1 year ago

It seems like an invalid JSON input is the only case where this is needed, and in that case there will be no ID to wrangle anyway. The ParseRequests function already returns a *jrpc2.Error in case of failure (and that already marshals to a JSON-RPC error object), so could the proxy construct the reply message directly?

msg, jerr := json.Marshal(err)
if jerr != nil {
  panic(jerr) // probably do something better with this
}
resp := fmt.Sprintf(`{"jsonrpc":"2.0","id":null,"error":%s}`, string(msg))

or words to that effect.

Example: https://go.dev/play/p/9gzRLq6YPbM

brianmcgee commented 1 year ago

You make a fair point, it is quite a niche edge case. Rather than building a whole Response just to help with JSON marshalling your suggestion is much simpler.