api: response error in json instead of html for better rendering flexibility

This commit is contained in:
yusing
2025-01-29 11:50:08 +08:00
parent 4ad6257dab
commit d9b6b82f07
3 changed files with 43 additions and 10 deletions

View File

@@ -1,6 +1,7 @@
package err
import (
"encoding/json"
"errors"
"fmt"
)
@@ -46,3 +47,18 @@ func (err baseError) Withf(format string, args ...any) Error {
func (err *baseError) Error() string {
return err.Err.Error()
}
// MarshalJSON implements the json.Marshaler interface.
func (err *baseError) MarshalJSON() ([]byte, error) {
//nolint:errorlint
switch err := err.Err.(type) {
case Error, *withSubject:
return json.Marshal(err)
case json.Marshaler:
return err.MarshalJSON()
case interface{ MarshalText() ([]byte, error) }:
return err.MarshalText()
default:
return json.Marshal(err.Error())
}
}