Skip to content

Commit

Permalink
Provide more informative error for dynamic.dict when key is a string
Browse files Browse the repository at this point in the history
  • Loading branch information
sporto committed Nov 20, 2024
1 parent ec9cc3f commit 0f7aa26
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/gleam/dynamic.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -976,13 +976,17 @@ pub fn dict(
|> dict.to_list
|> list.try_map(fn(pair) {
let #(k, v) = pair
let value_error = case string(k) {
Ok(k) -> "values[" <> k <> "]"
_ -> "values"
}
use k <- result.try(
key_type(k)
|> map_errors(push_path(_, "keys")),
)
use v <- result.try(
value_type(v)
|> map_errors(push_path(_, "values")),
|> map_errors(push_path(_, value_error)),
)
Ok(#(k, v))
}),
Expand Down
7 changes: 7 additions & 0 deletions test/gleam/dynamic_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,13 @@ pub fn dict_test() {
dict.from_list([#("a", 1), #("b", 2)])
|> dynamic.from
|> dynamic.dict(dynamic.string, dynamic.string)
|> should.equal(
Error([DecodeError(expected: "String", found: "Int", path: ["values[a]"])]),
)

dict.from_list([#(1, 1), #(2, 2)])
|> dynamic.from
|> dynamic.dict(dynamic.int, dynamic.string)
|> should.equal(
Error([DecodeError(expected: "String", found: "Int", path: ["values"])]),
)
Expand Down

0 comments on commit 0f7aa26

Please sign in to comment.