fix(netxlite/errorsx): serialize directly to JSON (#491)

This simplifies serializing errors to `*string`. It did not
occur to me before. It seems quite a nice improvement.

Part of https://github.com/ooni/probe/issues/1591
This commit is contained in:
Simone Basso 2021-09-08 17:42:36 +02:00 committed by GitHub
parent 957185d659
commit 18b2eb37ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 0 deletions

View File

@ -1,5 +1,7 @@
package errorsx
import "encoding/json"
// ErrWrapper is our error wrapper for Go errors. The key objective of
// this structure is to properly set Failure, which is also returned by
// the Error() method, to be one of the OONI failure strings.
@ -60,3 +62,8 @@ func (e *ErrWrapper) Error() string {
func (e *ErrWrapper) Unwrap() error {
return e.WrappedErr
}
// MarshalJSON converts an ErrWrapper to a JSON value.
func (e *ErrWrapper) MarshalJSON() ([]byte, error) {
return json.Marshal(e.Failure)
}

View File

@ -1,6 +1,7 @@
package errorsx
import (
"encoding/json"
"errors"
"io"
"testing"
@ -23,4 +24,19 @@ func TestErrWrapper(t *testing.T) {
t.Fatal("cannot unwrap error")
}
})
t.Run("MarshalJSON", func(t *testing.T) {
wrappedErr := &ErrWrapper{
Failure: FailureEOFError,
WrappedErr: io.EOF,
}
data, err := json.Marshal(wrappedErr)
if err != nil {
t.Fatal(err)
}
s := string(data)
if s != "\""+FailureEOFError+"\"" {
t.Fatal("invalid serialization", s)
}
})
}