Go 错误处理 errors
source link: https://wnanbei.github.io/post/go-%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86-errors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
errors
用于增强 Go 的错误处理能力。
Errors
error
类型为一个接口,其定义为:
type error interface {
Error() string
}
Error
Error()
函数返回一个字符串,用以表示这个 error
类型。
func (e *error) Error() string (
return e.msg
)
Go 1.13 中新增,可以将 error
嵌套起来,形成多层结构。
简单的嵌套方法,用 Errorf()
和 %w
:
e := errors.New("原始错误")
w := fmt.Errorf("Wrap了一个错误%w", e)
复杂的自定义类型需要拥有 Unwrap()
方法的 error
类型。
Unwrap()
的定义举例:
type NewError struct {
err error
msg string
}
func (e *NewError) Error() string {
return e.err.Error() + e.msg
}
func (e *NewError) Unwrap() error (
return e.err
)
e := errors.New("原始错误")
w := &NewError{err: e, msg: "wrap了一个错误"}
Unwrap
Go 1.13 新增,这个函数可以把嵌套在 error
中的 error
取出。
func Unwrap(err error) error
用来判断 err
或者其嵌套链中,是否有 target
类型的异常,只能判断已经生成的特定类型 error
,也就是所谓的哨兵异常。
func Is(err error, target error) bool
if errors.Is(err, os.ErrExist)
用来判断 err
或者其嵌套链中,是否有 target
的异常,如果有,就将符合类型的 err
赋值给 target
。
这种方式只能判断指定的自定义异常类型,也就是 struct
。
func As(err error, target interface{}) bool
var tar *os.PathError
if errors.As(err, &tar) {
fmt.Println(perr.Path)
}
Licensed under MIT License
最后更新于 2021-11-09 23:34:24
Recommend
-
71
PHP 中的 Exception, Error, ThrowablePHP 中将代码自身异常(一般是环境或者语法非法所致)称作错误 Error,将运行中出现的逻辑错误称为异常 Exception错误是没法通过代码处理的,而异常则可以通过 try/catch 来处理PHP7 中出现了 Throwable 接口,该接口由 Error...
-
67
概述在实际工程项目中,我们希望通过程序的错误信息快速定位问题,但是又不喜欢错误处理代码写的冗余而又啰嗦。Go语言没有提供像Java、C#语言中的try...catch异常处理方式,而是通过函数返回值逐层往上抛。这种设计,鼓励工程师在代码中显式的检查错误,而非忽略错...
-
70
koa2 中的错误处理以及中间件设计原理
-
70
本章内容 理解浏览器报告的错误 处理错误 调试JavaScript代码 错误处理 错误处理在程序设计中的重要性是一定的。任何有影响力的Web应用程序都需要一套完善的错误处理机制。 try-catch语句 try { // 可能会导致错误的代码 }
-
75
当我们开发spring web应用程序时,对于如IOException,ClassNotFoundException之类的检查异常,往往编译器会提示程序员采用try-catch进行显式捕获,而对于像ClassCastException,NullPointerE
-
67
一次关于walle项目的部署出错经历,以及解决错误所遇到的坑
-
5
V2EX › 程序员 [postgresql] 表查询错误 psycopg2.errors.UndefinedTable Outliver0 ·...
-
5
注:本文隶属于《理解ASP.NET Core》系列文章,请查看置顶博客或点击此处查看全文目录 使用中间件进行错误处理 开发人员异常页
-
5
ansible条件errors处理 精选 原创 哭泣的馒头 2023-02-21 09:22:45...
-
5
VS Code出现#include errors detected错误 C/C++tlanyan最近下载了某开源软件的源码,其使用
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK