fix: nil when printing error in edge cases

This commit is contained in:
yusing 2025-05-13 19:40:04 +08:00
parent a1f2a84a16
commit 1e24765b17
4 changed files with 13 additions and 5 deletions

View file

@ -36,8 +36,11 @@ func (err *baseError) Subjectf(format string, args ...any) Error {
return err.Subject(format)
}
func (err baseError) With(extra error) Error {
return &nestedError{&err, []error{extra}}
func (err *baseError) With(extra error) Error {
if extra == nil {
return err
}
return &nestedError{&baseError{err.Err}, []error{extra}}
}
func (err baseError) Withf(format string, args ...any) Error {

View file

@ -31,7 +31,7 @@ func (h *Hint) String() string {
return h.Error()
}
func DoYouMean(s string) *Hint {
func DoYouMean(s string) error {
if s == "" {
return nil
}

View file

@ -78,8 +78,10 @@ func (err *nestedError) fmtError(appendLine appendLineFunc) []byte {
}
if err.Err != nil {
buf := appendLine(nil, err.Err, 0)
if len(err.Extras) > 0 {
buf = append(buf, '\n')
buf = appendLines(buf, err.Extras, 1, appendLine)
}
return buf
}
return appendLines(nil, err.Extras, 0, appendLine)

View file

@ -87,6 +87,9 @@ func Join(errors ...error) Error {
func JoinLines(main error, errors ...string) Error {
errs := make([]error, len(errors))
for i, err := range errors {
if err == "" {
continue
}
errs[i] = newError(err)
}
return &nestedError{Err: main, Extras: errs}