refactor: M-02 添加 errs 包提供错误处理基础设施
This commit is contained in:
33
internal/errs/common.go
Normal file
33
internal/errs/common.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package errs
|
||||
|
||||
import "errors"
|
||||
|
||||
// 通用错误
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrDuplicate = errors.New("duplicate")
|
||||
)
|
||||
|
||||
// CLI 错误
|
||||
var (
|
||||
ErrMissingRequiredFlag = errors.New("missing required flag")
|
||||
ErrInvalidFlagValue = errors.New("invalid flag value")
|
||||
)
|
||||
|
||||
// Repository 错误
|
||||
var (
|
||||
ErrExecFailed = errors.New("database exec failed")
|
||||
ErrQueryFailed = errors.New("database query failed")
|
||||
)
|
||||
|
||||
// Overlay 错误
|
||||
var (
|
||||
ErrOverlayNotMatched = errors.New("overlay did not match")
|
||||
ErrNestedOutput = errors.New("output directory must not be nested inside source directory")
|
||||
ErrOutputExists = errors.New("output directory already exists")
|
||||
ErrSourceNotDir = errors.New("source must be a directory")
|
||||
ErrPatchFileNotFound = errors.New("patch file not found")
|
||||
ErrPatchApplyFailed = errors.New("failed to apply patch")
|
||||
)
|
||||
28
internal/errs/test_helpers.go
Normal file
28
internal/errs/test_helpers.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package errs
|
||||
|
||||
import "testing"
|
||||
|
||||
// AssertErrorContains 检查错误是否包含预期子字符串
|
||||
// 用于替代脆弱的直接字符串匹配
|
||||
func AssertErrorContains(t *testing.T, err error, wantSubstring string) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatalf("expected error containing %q, got nil", wantSubstring)
|
||||
}
|
||||
if !containsSubstring(err.Error(), wantSubstring) {
|
||||
t.Fatalf("error = %q, want containing %q", err.Error(), wantSubstring)
|
||||
}
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
return len(substr) <= len(s) && containsAt(s, substr, 0)
|
||||
}
|
||||
|
||||
func containsAt(s, substr string, start int) bool {
|
||||
for i := start; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user