当前位置:网站首页>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 .
边栏推荐
- Wechat applet Bluetooth connects hardware devices and communicates. Applet Bluetooth automatically reconnects due to abnormal distance. JS realizes CRC check bit
- Sidecar mode
- Dynamic memory management
- zabbix_ Get test database failed
- 【Shell】清理nohup.out文件
- Reptile exercises (III)
- TCC of distributed transaction solutions
- PTA 天梯赛练习题集 L2-002 链表去重
- C#可空类型
- Mysql-centos7 install MySQL through yum
猜你喜欢
sql查询:将下一行减去上一行,并做相应的计算
目标检测中的BBox 回归损失函数-L2,smooth L1,IoU,GIoU,DIoU,CIoU,Focal-EIoU,Alpha-IoU,SIoU
CTFshow--常用姿势
nVisual网络可视化
Différenciation et introduction des services groupés, distribués et microservices
集群、分布式、微服务的区别和介绍
什么是消息队列?
The 2022 China low / no code Market Research and model selection evaluation report was released
Red Hat安装内核头文件
Web Authentication API兼容版本信息
随机推荐
驱动开发中platform设备驱动架构详解
Get the way to optimize the one-stop worktable of customer service
如果不知道这4种缓存模式,敢说懂缓存吗?
cf:C. Column Swapping【排序 + 模拟】
Differences and introduction of cluster, distributed and microservice
关于服装ERP,你知道多少?
PTA 天梯赛练习题集 L2-003 月饼 测试点2,测试点3分析
Modes of optical fiber - single mode and multimode
ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用shap决策图结合LightGBM模型实现异常值检测案例之详细攻略
Red Hat安装内核头文件
I didn't know it until I graduated -- the principle of HowNet duplication check and examples of weight reduction
sql查询:将下一行减去上一行,并做相应的计算
[daily training -- Tencent selected 50] 292 Nim games
Hcip seventh operation
Bbox regression loss function in target detection -l2, smooth L1, IOU, giou, Diou, ciou, focal eiou, alpha IOU, Siou
Three level menu data implementation, nested three-level menu data
【日常训练--腾讯精选50】235. 二叉搜索树的最近公共祖先
AI人脸编辑让Lena微笑
Introduction to distributed transactions
苹果cms V10模板/MXone Pro自适应影视电影网站模板