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:
parent
957185d659
commit
18b2eb37ff
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user