Skip to content

Augment Exception implementations with additional data #9264

Open
@Blacksmoke16

Description

@Blacksmoke16

Thoughts on adding additional ivars to select exception types to expose additional information about the exception? For example, TypeCastError, only exposes the exception message, such as cast from Nil to String failed. However, there isn't a way to know typed failed to cast to what type.

It would be nice to be able to do something like:

require "json"
 
def convert(type : String.class, data)
  data.as_s
rescue ex : TypeCastError
  raise "Expected #{type} but got #{ex.from_type}"
end
 
convert String, JSON.parse("null")

Currently the only way to do this is to parse the type from the message. However, this is assuming the specific instance of TypeCastError has that data in the message in the first place.

Granted, not all exceptions would need this. I could see like IndexError or KeyError including a reference to the index/key that caused the exception.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions