I use autodie to handle exceptions from built-ins. Unfortunately its scope is lexical, autodie does not work with methods. Is it possible to throw exceptions from my class methods so that they are handled in the same manner like autodie exceptions. In short, I dont want users of my classes to handle exceptions in two ways - one with the rich exception class that autodie provides for built-ins and another for the simple "die if ..." that my code throws.
If it helps, I use Moose to build my classes
If you want your exceptions to be like those in autodie, then I can think of two options:
Use or inherit from the
autodie::exceptionclass.This is pretty straightforward, just
perldoc autodie::exceptionand note which arguments it needs when creating new objects. You might find that inheriting fromautodie::exceptionprovides you more flexibility or functionality, in which case you should do that.Tell
autodieto use your own exception class.This is a little more tricky, but not that hard:
You can then use
my::autodiein your code (with lexical scope), but whenever it throws an exception, it will create and throw an object frommy::exception::classrather than fromautodie::exception. This is probably overkill for what you want, but it's very handy if you want to, say, extendautodie's exceptions to provide stack-backtraces, localisation, or other functionality.