当前位置:网站首页>Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
2022-07-07 00:38:00 【剑客阿良_ALiang】
学习笔记,写到哪是哪。
接着上一篇文章:Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)_剑客阿良_ALiang的博客-CSDN博客
目前gorm对数据库的一些操作基本了解。
本篇主要测试一下gorm的异常处理方式。
项目地址:github地址
可以先看看gorm定义的异常,代码如下:
var (
// ErrRecordNotFound record not found error
ErrRecordNotFound = logger.ErrRecordNotFound
// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidTransaction = errors.New("invalid transaction")
// ErrNotImplemented not implemented
ErrNotImplemented = errors.New("not implemented")
// ErrMissingWhereClause missing where clause
ErrMissingWhereClause = errors.New("WHERE conditions required")
// ErrUnsupportedRelation unsupported relations
ErrUnsupportedRelation = errors.New("unsupported relations")
// ErrPrimaryKeyRequired primary keys required
ErrPrimaryKeyRequired = errors.New("primary key required")
// ErrModelValueRequired model value required
ErrModelValueRequired = errors.New("model value required")
// ErrInvalidData unsupported data
ErrInvalidData = errors.New("unsupported data")
// ErrUnsupportedDriver unsupported driver
ErrUnsupportedDriver = errors.New("unsupported driver")
// ErrRegistered registered
ErrRegistered = errors.New("registered")
// ErrInvalidField invalid field
ErrInvalidField = errors.New("invalid field")
// ErrEmptySlice empty slice found
ErrEmptySlice = errors.New("empty slice found")
// ErrDryRunModeUnsupported dry run mode unsupported
ErrDryRunModeUnsupported = errors.New("dry run mode unsupported")
// ErrInvalidDB invalid db
ErrInvalidDB = errors.New("invalid db")
// ErrInvalidValue invalid value
ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
// ErrInvalidValueOfLength invalid values do not match length
ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
// ErrPreloadNotAllowed preload is not allowed when count is used
ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
)
编写一个接口来测试一下异常。
在student_service下新增TestError方法。
方法代码如下:
//测试gorm异常
func (t StudentImpl) TestError() rsp.ResponseMsg {
log.Logger.Info("测试gorm异常")
_db := mysql.GetDB()
var _student db_entity.Student
if _err := _db.Where("del_flag = 1").First(&_student).Error; _err != nil {
if errors.Is(_err, gorm.ErrRecordNotFound) {
fmt.Println("error is ErrRecordNotFound")
}
log.Logger.Panic("error -> ", log.Any("error", _err))
}
log.Logger.Debug("student -> ", log.Any("student", _student))
return *rsp.SuccessMsg("测试成功")
}
如果sql无法获取到record,会报出ErrRecordNotFound异常。
controller层增加接口代码,如下:
//测试gorm异常
func (s StudentController) TestError(context *gin.Context) {
log.Logger.Info("测试gorm异常接口")
_rsp := services.StudentServ.TestError()
context.JSON(http.StatusOK, _rsp)
}
验证一下接口执行后的打印输出。
可以看到是全局捕获的异常响应报文。
小结
在项目开发中,异常处理是比较必要的。
最近有点忙,也有所体悟,有时候需要把压力释放一下,但是需要合理有效的方式。有时候需要把压力往身边分担下,并不是什么时候都需要扛下所有。
边栏推荐
- 高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
- Flinksql 读写pgsql
- Reading notes of Clickhouse principle analysis and Application Practice (6)
- Common skills and understanding of SQL optimization
- Forkjoin is the most comprehensive and detailed explanation (from principle design to use diagram)
- SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server
- EMMC打印cqhci: timeout for tag 10提示分析与解决
- Modes of optical fiber - single mode and multimode
- Go language context explanation
- TCC of distributed transaction solutions
猜你喜欢
上海字节面试问题及薪资福利
ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用shap决策图结合LightGBM模型实现异常值检测案例之详细攻略
Interview questions and salary and welfare of Shanghai byte
随机生成session_id
SAP webservice 测试出现404 Not found Service cannot be reached
驱动开发中platform设备驱动架构详解
三级菜单数据实现,实现嵌套三级菜单数据
Distributed global ID generation scheme
Common skills and understanding of SQL optimization
ForkJoin最全详解(从原理设计到使用图解)
随机推荐
什么是消息队列?
判断文件是否为DICOM文件
404 not found service cannot be reached in SAP WebService test
Nodejs get client IP
Flinksql read / write PgSQL
Reading the paper [sensor enlarged egocentric video captioning with dynamic modal attention]
《2022中国低/无代码市场研究及选型评估报告》发布
拼多多新店如何获取免费流量,需要从哪些环节去优化,才能有效提升店内免费流量
Mysql-centos7 install MySQL through yum
【Shell】清理nohup.out文件
常用消息队列有哪些?
毕业之后才知道的——知网查重原理以及降重举例
【日常训练--腾讯精选50】292. Nim 游戏
力扣102题:二叉树的层序遍历
Type de texte de commutation d'entrée et de mot de passe de l'applet natif
PowerPivot——DAX(函数)
Interview skills of software testing
[reading of the paper] a multi branch hybrid transformer network for channel terminal cell segmentation
Industrial Finance 3.0: financial technology of "dredging blood vessels"
ForkJoin最全详解(从原理设计到使用图解)