I have a class that reads configuration. Now the problem is that I don't know how to report errors from this class.
Using die
isn't 开发者_JAVA百科sufficient, since the configuration is parametric, and errors are common.
The situation is complicated by the fact, that I'm invoking the read function in Moose
BUILD
method. Because this usage significantly improves readability when the class is used, I would like to keep it this way.
What is wrong with die
? It throws an exception that you can capture and process as needed. In fact Moose itself throws exception on validation errors.
You might want to look at Carp for its croak()
function. From its documentation:
The Carp routines are useful in your own modules because they act like die() or warn(), but with a message which is more likely to be useful to a user of your module. In the case of cluck, confess, and longmess that context is a summary of every call in the call-stack. For a shorter message you can use carp or croak which report the error as being from where your module was called.
Used along with Try::Tiny you get a more powerful, flexible, and descriptive solution than matching good old die with eval. You don't have to worry about the edge cases that cause $@ to provide bad information, for example. And your exceptions can be more accurately descriptive, as well as more detailed. With Carp, you can even make your croaks behave like confess, providing a detailed stack trace, which makes it easier to see exactly where a problem is originating.
精彩评论