Is it better to croak() or to die() when something bad happens in Perl?

后端 未结 6 1209
无人及你
无人及你 2021-02-18 22:12

perlcritic complaints that the following code, some boilerplate DBI stuff that works perfectly fine, should croak instead of die:

# Connect to database
my $db_ha         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 22:41

    I usually use the following:

    • die "string" for fatal messages you want to directly communicate to the user. I mostly do this in scripts.
    • die $object for full blown exception objects, although most exception classes will have throw method doing that for you. This is for when your caller should be able to tell what kind of error you throw, and maybe even extract information out of it. If you're using Moose, check out Throwable and Throwable-X
    • croak "message" like Adrian said is for when your user has done something wrong, and you want to report the error at whatever called your code. Functions and API level methods are usual cases for this.
    • confess "message" for library errors where I don't see the usefulness of an exception yet. These are usually runtime errors you assume to be a mistake, rather than an exceptional condition. It can make sense to use exceptions for these, especially if you have a large project that uses exceptions already. But it's a good, nice and easy way to get a stacktrace with the error.

提交回复
热议问题