三层代码就类似一个中间件,后面还可以扩展为函数式中间件,并且无框架无关.
1. service出错如何接收?
(1). service:
// 返回追加了两个参数
func(this *BookService) getList(req *BookListRequest) (*Models.AdminLoges, error) {
books := &Models.AdminLoges{}
// 如果在连接池错误或sql查询时出现错误,或者有逻辑需要判断错误
err := Init.GetDB().Limit(req.Size).Order("id desc").Find(books).Error
if err != nil {
return nil, err
} else {
return books, nil
}
}
func(this *BookService) getDetail(req *BookDetailRequest) (*Models.AdminLogs, error) {
book := &Models.AdminLogs{}
// 判断为空
if Init.GetDB().Find(book, req.Id).RowsAffected != 1 {
return nil, fmt.Errorf("no record")
} else {
return book, nil
}
}
(2). endpoint:
func BookListEndpoint(book *BookService) Lib.Endpoint {
return func(ctx *gin.Context, request interface{}) (interface{}, error) {
req := request.(*BookListRequest)
// 这里改为两个值接收
result, err := book.getList(req)
return &BookListResponse{Result: result}, err // 将err返回出去
}
}
func BookDetailEndpoint(book *BookService) Lib.Endpoint {
return func(ctx *gin.Context, request interface{}) (interface{}, error) {
req := request.(*BookDetailRequest)
result, err := book.getDetail(req)
return &BookDetailResponse{Result: result}, err
}
}
2. panic错误处理:
(1). service:
func(this *BookService) getList(req *BookListRequest) (*Models.AdminLoges, error) {
panic("出错了")
books := &Models.AdminLoges{}
......
}
(2). serviceHelp:
func RegisterHandler(encodeFunc EncodeRequestFunc, endpoint Endpoint, decodeFunc DecodeResponseFunc) func (ctx *gin.Context) {
return func(ctx *gin.Context) {
// 捕获panic错误,这里也可以优化,不写在这里,可以写在外部,使用装饰器的方式加进来
defer func() {
if r := recover(); r != nil {
ctx.JSON(500, gin.H{"error": fmt.Sprintf("fatal error:%s", r)})
return
}
}()
// 获取参数
request, err := encodeFunc(ctx)
......
}
}