如何在GQL Schema中处理nil值避免算术表达式参数错误
解决GraphQL Schema中nil值引发的ArithmeticError问题
问题分析
你的代码在square_plot为非nil的float值时能正常转换为平方英尺,但当该值为nil时,直接执行source.square_plot*10.7639会触发**(ArithmeticError) bad argument in arithmetic expression**,导致服务器返回内部错误。另外原代码中field :square_plot_ft的条件判断写在resolve外部是无效的——这部分逻辑在schema定义阶段执行,无法获取到运行时的source数据。
修复方案
需要在resolve函数内部先对source.square_plot进行nil值与有效性校验,只有当它存在且为有效正数时才执行计算,否则返回nil(或业务需求的默认值)。
修正后的代码(模式匹配写法)
field(:square_plot, :float) # 数据库中该变量值可为`50.0`或`nil` field :square_plot_ft, :float do resolve(fn _args, %{source: source} -> case source.square_plot do value when is_float(value) and value > 0 -> {:ok, Float.round(value * 10.7639, 0)} _ -> {:ok, nil} # 可根据需求替换为0.0等默认值 end end) end
修正后的代码(条件判断写法)
field(:square_plot, :float) field :square_plot_ft, :float do resolve(fn _args, %{source: source} -> if is_float(source.square_plot) and source.square_plot > 0 do {:ok, Float.round(source.square_plot * 10.7639, 0)} else {:ok, nil} end end) end
效果验证
- 当
square_plot为50.0时,square_plot_ft会返回538.0,与之前的正常响应一致。 - 当
square_plot为nil时,square_plot_ft会返回nil(或你设置的默认值),不会再触发服务器内部错误,GraphQL响应会正常返回"squarePlotFt": null。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

