写一个注册接口遇到的空指针疑问

请问为何会报空指针的错误?#

Code:

代码已被折叠,点此展开

Error:

2022/12/23 21:24:52 /Users/tom/go/src/Learn/main.go:67 record not found
[2.519ms] [rows:0] SELECT * FROM `users` WHERE phone = '13888888888' AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1


2022/12/23 21:24:52 [Recovery] 2022/12/23 - 21:24:52 panic recovered:
GET /api/v1/register HTTP/1.1
Host: localhost
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 389
Content-Type: multipart/form-data; boundary=--------------------------462561745692434217366880
Postman-Token: 81959ddb-4e76-449b-9412-3f7d20101178
User-Agent: PostmanRuntime/7.29.2


runtime error: invalid memory address or nil pointer dereference
/usr/local/Cellar/go/1.18.4/libexec/src/runtime/panic.go:220 (0x104a4f5)
        panicmem: panic(memoryError)
/usr/local/Cellar/go/1.18.4/libexec/src/runtime/signal_unix.go:818 (0x104a4c5)
        sigpanic: panicmem()
/Users/tom/go/src/Learn/main.go:69 (0x15500a5)
        IsPhoneExist: if user.ID != 0 {
/Users/tom/go/src/Learn/main.go:38 (0x154fd64)
        main.func1: if IsPhoneExist(DB, phone) {
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148c861)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/recovery.go:101 (0x148c84c)
        CustomRecoveryWithWriter.func1: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148b946)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/logger.go:240 (0x148b929)
        LoggerWithConfig.func1: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148aa10)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:616 (0x148a678)
        (*Engine).handleHTTPRequest: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:572 (0x148a1bc)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/Cellar/go/1.18.4/libexec/src/net/http/server.go:2916 (0x129149a)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/Cellar/go/1.18.4/libexec/src/net/http/server.go:1966 (0x128c496)
最佳答案

gorm 判断数据是否存在,先用 error 判断。这里报错是 gorm 判断没对

2年前 评论
讨论数量: 3

没有报错信息,看不出来什么问题。

2年前 评论
Scrooge (楼主) 2年前

gorm 判断数据是否存在,先用 error 判断。这里报错是 gorm 判断没对

2年前 评论