当前位置:网站首页>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 .

边栏推荐
- 力扣102题:二叉树的层序遍历
- Interview questions and salary and welfare of Shanghai byte
- 【已解决】记一次EasyExcel的报错【读取xls文件时全表读不报错,指定sheet名读取报错】
- 得物客服一站式工作台卡顿优化之路
- STM32 key state machine 2 - state simplification and long press function addition
- Explication contextuelle du langage Go
- Différenciation et introduction des services groupés, distribués et microservices
- 《ClickHouse原理解析与应用实践》读书笔记(6)
- mac版php装xdebug环境(m1版)
- Industrial Finance 3.0: financial technology of "dredging blood vessels"
猜你喜欢

SAP ABAP BDC (batch data communication) -018

Interview skills of software testing

分布式全局ID生成方案

【SQL实战】一条SQL统计全国各地疫情分布情况

SAP webservice 测试出现404 Not found Service cannot be reached

SQL query: subtract the previous row from the next row and make corresponding calculations

Realize GDB remote debugging function between different network segments

Forkjoin is the most comprehensive and detailed explanation (from principle design to use diagram)

数据中心为什么需要一套基础设施可视化管理系统

每秒10W次分词搜索,产品经理又提了一个需求!!!(收藏)
随机推荐
[云原生]微服务架构是什么?
JVM the truth you need to know
C#可空类型
2pc of distributed transaction solution
Data storage 3
爬虫练习题(三)
【日常训练--腾讯精选50】292. Nim 游戏
Go 语言的 Context 详解
Web architecture design process
【已解决】记一次EasyExcel的报错【读取xls文件时全表读不报错,指定sheet名读取报错】
Realize GDB remote debugging function between different network segments
苹果cms V10模板/MXone Pro自适应影视电影网站模板
Win configuration PM2 boot auto start node project
绕过open_basedir
成为资深IC设计工程师的十个阶段,现在的你在哪个阶段 ?
PTA 天梯赛练习题集 L2-002 链表去重
nVisual网络可视化
Bat instruction processing details
Explication contextuelle du langage Go
WEB架构设计过程