fix error formatting

This commit is contained in:
yusing 2025-01-26 05:26:18 +08:00
parent 9b66772a12
commit 254224c0e8

View file

@ -10,6 +10,8 @@ import (
type withSubject struct { type withSubject struct {
Subjects []string `json:"subjects"` Subjects []string `json:"subjects"`
Err error `json:"err"` Err error `json:"err"`
pendingSubject string
} }
const subjectSep = " > " const subjectSep = " > "
@ -30,17 +32,26 @@ func PrependSubject(subject string, err error) error {
case Error: case Error:
return err.Subject(subject) return err.Subject(subject)
} }
return &withSubject{[]string{subject}, err} return &withSubject{[]string{subject}, err, ""}
} }
func (err *withSubject) Prepend(subject string) *withSubject { func (err *withSubject) Prepend(subject string) *withSubject {
if subject == "" {
return err
}
clone := *err clone := *err
if subject != "" { switch subject[0] {
switch subject[0] { case '[', '(', '{':
case '[', '(', '{': // since prepend is called in depth-first order,
clone.Subjects[len(clone.Subjects)-1] += subject // the subject of the index is not yet seen
default: // add it when the next subject is seen
clone.Subjects = append(clone.Subjects, subject) clone.pendingSubject += subject
default:
clone.Subjects = append(clone.Subjects, subject)
if clone.pendingSubject != "" {
clone.Subjects[len(clone.Subjects)-1] = subject + clone.pendingSubject
clone.pendingSubject = ""
} }
} }
return &clone return &clone