当前位置:网站首页>Go language learning notes - Gorm use - Gorm processing errors | web framework gin (10)
Go language learning notes - Gorm use - Gorm processing errors | web framework gin (10)
2022-07-07 05:56:00 【Swordsman a Liang_ ALiang】
Learning notes , Where is where .
Next to the previous article :Go English learning notes - gorm Use - Native sql、 Named parameters 、Rows、ToSQL | Web frame Gin( Nine )_ Swordsman a Liang _ALiang The blog of -CSDN Blog
at present gorm Have a basic understanding of some database operations .
This article mainly tests gorm Exception handling method of .
Project address :github Address
You can have a look first gorm Defined exception , The code is as follows :
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")
)
Write an interface to test the exception .
stay student_service Add below TestError Method .
The method code is as follows :
// test gorm abnormal
func (t StudentImpl) TestError() rsp.ResponseMsg {
log.Logger.Info(" test gorm abnormal ")
_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(" Test success ")
}
If sql Can't get record, It will be reported ErrRecordNotFound abnormal .
controller Add interface code in layer , as follows :
// test gorm abnormal
func (s StudentController) TestError(context *gin.Context) {
log.Logger.Info(" test gorm Exception interface ")
_rsp := services.StudentServ.TestError()
context.JSON(http.StatusOK, _rsp)
}
Verify the printout after the interface is executed .
It can be seen that the exception response message captured globally .
Summary
In project development , Exception handling is quite necessary .
A little busy recently , Also have some understanding , Sometimes you need to release the pressure , But we need a reasonable and effective way . Sometimes you need to share the pressure with others , It's not always necessary to carry all .
边栏推荐
- [云原生]微服务架构是什么?
- Forkjoin is the most comprehensive and detailed explanation (from principle design to use diagram)
- 微信小程序蓝牙连接硬件设备并进行通讯,小程序蓝牙因距离异常断开自动重连,js实现crc校验位
- Polynomial locus of order 5
- async / await
- mac版php装xdebug环境(m1版)
- Data storage 3
- Mybaits multi table query (joint query, nested query)
- Go语学习笔记 - gorm使用 - 原生sql、命名参数、Rows、ToSQL | Web框架Gin(九)
- SAP ABAP BDC (batch data communication) -018
猜你喜欢
AI face editor makes Lena smile
TCC of distributed transaction solutions
Go语学习笔记 - gorm使用 - gorm处理错误 | Web框架Gin(十)
力扣102题:二叉树的层序遍历
Interview questions and salary and welfare of Shanghai byte
ForkJoin最全详解(从原理设计到使用图解)
SQLSTATE[HY000][1130] Host ‘host. docker. internal‘ is not allowed to connect to this MySQL server
每秒10W次分词搜索,产品经理又提了一个需求!!!(收藏)
JVM the truth you need to know
Digital IC interview summary (interview experience sharing of large manufacturers)
随机推荐
往图片添加椒盐噪声或高斯噪声
随机生成session_id
集群、分布式、微服务的区别和介绍
PowerPivot——DAX(函数)
Explication contextuelle du langage Go
集群、分布式、微服務的區別和介紹
Loss function and positive and negative sample allocation in target detection: retinanet and focal loss
An example of multi module collaboration based on NCF
Polynomial locus of order 5
Digital IC interview summary (interview experience sharing of large manufacturers)
Interview questions and salary and welfare of Shanghai byte
SAP Spartacus checkout 流程的扩展(extend)实现介绍
Forkjoin is the most comprehensive and detailed explanation (from principle design to use diagram)
404 not found service cannot be reached in SAP WebService test
Sidecar mode
PTA 天梯赛练习题集 L2-003 月饼 测试点2,测试点3分析
【Shell】清理nohup.out文件
爬虫练习题(三)
Pytorch builds neural network to predict temperature
zabbix_ Get test database failed