Skip to content

Commit c88d84b

Browse files
committed
make decode error messages more descriptive
1 parent 11721ab commit c88d84b

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

lib/msgpack/decode_error.ex

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,30 @@ defmodule Msgpack.DecodeError do
22
defexception [:message, :reason]
33

44
@impl true
5+
def message(%{reason: :unexpected_eof}) do
6+
"Unexpected end of file. The MessagePack binary is incomplete."
7+
end
8+
9+
def message(%{reason: {:unknown_prefix, prefix}}) do
10+
"Unknown type prefix: #{prefix}. The byte `0x#{Integer.to_string(prefix, 16)}` is not a valid MessagePack type marker."
11+
end
12+
13+
def message(%{reason: {:trailing_bytes, rest}}) do
14+
"Trailing bytes remaining after decoding. A valid MessagePack binary must have exactly one root object. Remaining data: #{inspect(rest)}"
15+
end
16+
17+
def message(%{reason: {:max_depth_reached, max_depth}}) do
18+
"Maximum nesting depth of #{max_depth} reached. This limit can be configured with the `:max_depth` option."
19+
end
20+
21+
def message(%{reason: {:max_byte_size_exceeded, max_size}}) do
22+
"A declared object size exceeds the maximum of #{max_size} bytes. This limit can be configured with the `:max_byte_size` option."
23+
end
24+
25+
def message(%{reason: :invalid_timestamp}) do
26+
"Invalid timestamp format. The nanosecond field must be less than 1,000,000,000."
27+
end
28+
529
def message(exception) do
630
"Failed to decode MessagePack binary. Reason = #{inspect(exception.reason)}"
731
end

test/msgpack_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,20 @@ defmodule MsgpackTest do
162162
Msgpack.decode!(input)
163163
end
164164
end
165+
166+
test "raises an error with a descriptive message" do
167+
assert_raise Msgpack.DecodeError, "Unexpected end of file. The MessagePack binary is incomplete.", fn ->
168+
Msgpack.decode!(<<0x81, 0xA3, "f">>)
169+
end
170+
171+
assert_raise Msgpack.DecodeError, "Unknown type prefix: 193. The byte `0xC1` is not a valid MessagePack type marker.", fn ->
172+
Msgpack.decode!(<<0xC1>>)
173+
end
174+
175+
assert_raise Msgpack.DecodeError, "Maximum nesting depth of 2 reached. This limit can be configured with the `:max_depth` option.", fn ->
176+
Msgpack.decode!(<<0x91, 0x91, 0x91, 1>>, max_depth: 2)
177+
end
178+
end
165179
end
166180

167181
describe "Property Tests" do

0 commit comments

Comments
 (0)