encoding/textpb: marshal Any as regular message if unable to expand

If there are any kind of errors in trying to expand the Any message,
always fallback to marshaling it as regular message.  This makes it
consistent with V1 and C++ libs.

Change-Id: I007414c1767e682623c45d4dd8c82b9998f61781
Reviewed-on: https://go-review.googlesource.com/c/156257
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
diff --git a/encoding/textpb/encode.go b/encoding/textpb/encode.go
index 62ebc63..2062ec2 100644
--- a/encoding/textpb/encode.go
+++ b/encoding/textpb/encode.go
@@ -78,10 +78,7 @@
 			// Return as is for nil or non-fatal error.
 			return msg, nerr.E
 		}
-		if err != protoregistry.NotFound {
-			return text.Value{}, err
-		}
-		// Continue on to marshal Any as a regular message if error is not found.
+		// For other errors, continue on to marshal Any as a regular message.
 	}
 
 	// Handle known fields.
diff --git a/encoding/textpb/encode_test.go b/encoding/textpb/encode_test.go
index a439df0..83cbbc5 100644
--- a/encoding/textpb/encode_test.go
+++ b/encoding/textpb/encode_test.go
@@ -5,6 +5,7 @@
 package textpb_test
 
 import (
+	"encoding/hex"
 	"math"
 	"strings"
 	"testing"
@@ -66,6 +67,15 @@
 	knownFields.Set(wire.Number(xd.Field), pval)
 }
 
+// dhex decodes a hex-string and returns the bytes and panics if s is invalid.
+func dhex(s string) []byte {
+	b, err := hex.DecodeString(s)
+	if err != nil {
+		panic(err)
+	}
+	return b
+}
+
 func TestMarshal(t *testing.T) {
 	tests := []struct {
 		desc    string
@@ -1051,6 +1061,23 @@
 `,
 		wantErr: true,
 	}, {
+		desc: "google.protobuf.Any message with invalid value",
+		mo: func() textpb.MarshalOptions {
+			m := &pb2.Nested{}
+			resolver := preg.NewTypes(m.ProtoReflect().Type())
+			return textpb.MarshalOptions{Resolver: resolver}
+		}(),
+		input: func() proto.Message {
+			m := &pb2.Nested{}
+			return impl.Export{}.MessageOf(&anypb.Any{
+				TypeUrl: string(m.ProtoReflect().Type().FullName()),
+				Value:   dhex("80"),
+			}).Interface()
+		}(),
+		want: `type_url: "pb2.Nested"
+value: "\x80"
+`,
+	}, {
 		desc: "google.protobuf.Any field",
 		mo:   textpb.MarshalOptions{Resolver: preg.NewTypes()},
 		input: func() proto.Message {