From 2a31984fc7cbebeb8e6f1908f9471aa97fa16e3a Mon Sep 17 00:00:00 2001 From: NoahLan <6995syu@163.com> Date: Thu, 20 Jul 2023 17:44:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20njson.MarshalSafe?= =?UTF-8?q?=20=E6=96=B9=E6=B3=95=EF=BC=8C=E5=90=8C=E6=97=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E4=B9=8B=E5=89=8D=E7=9A=84MarshalStrSafe=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- njson/json.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/njson/json.go b/njson/json.go index 67d93d8..0c55fa2 100644 --- a/njson/json.go +++ b/njson/json.go @@ -23,10 +23,23 @@ func MarshalStr(v any) (string, error) { return string(data), nil } +// MarshalSafe marshals v into json bytes. +// return an empty byte slice if an error occurred. +func MarshalSafe(v any) []byte { + ret, err := Marshal(v) + if err != nil { + return []byte{} + } + return ret +} + // MarshalStrSafe marshals v into a string. // return an empty string if an error occurred. func MarshalStrSafe(v any) string { - ret, _ := MarshalStr(v) + ret, err := MarshalStr(v) + if err != nil { + return "" + } return ret }