Skip to content

Commit

Permalink
Improve KeyError message for Context#[]
Browse files Browse the repository at this point in the history
  • Loading branch information
z64 committed Apr 18, 2018
1 parent 45d0ee9 commit ab37990
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
2 changes: 1 addition & 1 deletion spec/context_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe Discord::Context do

it "raises on a type that hasn't been stored" do
context = Discord::Context.new
expect_raises(Exception) do
expect_raises(KeyError, "Missing reference in context to Storage") do
context[Storage]
end
end
Expand Down
6 changes: 5 additions & 1 deletion src/discordcr-middleware/context.cr
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ module Discord

# Access a stored value by class
def [](clazz : T.class) : T forall T
@extensions[clazz.crystal_type_id].unsafe_as(T)
if reference = @extensions[clazz.crystal_type_id]?
reference.unsafe_as(T)
else
raise KeyError.new("Missing reference in context to #{T}")
end
end

# Store an object in this class. The object must be a `class`.
Expand Down

0 comments on commit ab37990

Please sign in to comment.