错误处理进阶
00:00
错误包装、检查与自定义错误
1. 错误包装
if err != nil {
return fmt.Errorf("failed to read config: %w", err)
}
// 检查
errors.Is(err, os.ErrNotExist)
errors.As(err, &pathErr)
2. 自定义错误
type AppError struct {
Code string
Message string
Cause error
}
func (e *AppError) Error() string { return e.Message }
func (e *AppError) Unwrap() error { return e.Cause }