在我的 GoLang GraphQL 查询中,我有以下方法(获取用户 ID 并返回配置文件数据):
"userProfile": &graphql.Field{
Type: UserProfileType,
Args: graphql.FieldConfigArgument{
"uid": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
uid := p.Args["uid"].(int)
u, err := db.GetUserProfile(p.Context.Value(handler.CtxId("currentUser")).(int), uid)
return u, err
},
},
Run Code Online (Sandbox Code Playgroud)
当用户 id 无效时db.GetUserProfile返回 nil 指针u和 nil error err,但 GraphQL 响应如下:
{
"data": { "userProfile": null },
"errors": [
{
"message": "runtime error: invalid memory address or nil pointer dereference",
"locations": []
}
]
}
Run Code Online (Sandbox Code Playgroud)
虽然当我像这样修改 GraphQL 代码时(显式 nil 检查并返回文字):
...
u, err := db.GetUserProfile(p.Context.Value(handler.CtxId("currentUser")).(int), uid)
if u == nil {
return nil, err
}
return u, err
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作,GraphQL 返回:
{
"data": {
"userProfile": null
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不显式检查 nil 的情况下进行管理并教 GraphQL 区分 nil 指针和 nil 文字?
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |