Groups | Search | Server Info | Login | Register
Groups > tw.bbs.comp.lang.perl > #28
| Path | csiph.com!news.mixmin.net!aioe.org!8hMd1CaCNyyZ+DubzAcuaA.user.46.165.242.75.POSTED!not-for-mail |
|---|---|
| From | Kang-min Liu <gugod@gugod.org> |
| Newsgroups | tw.bbs.comp.lang.perl |
| Subject | 轉換錯誤處理慣例 |
| Date | Mon, 12 Sep 2022 18:50:58 +0900 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <m1k068udj1.fsf@gugod.org> (permalink) |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=utf-8 |
| Content-Transfer-Encoding | 8bit |
| Injection-Info | gioia.aioe.org; logging-data="43205"; posting-host="8hMd1CaCNyyZ+DubzAcuaA.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org"; |
| User-Agent | Gnus/5.13 (Gnus v5.13) Emacs/28.1 (darwin) |
| Cancel-Lock | sha1:hAiqADTjtAEZP0EHbitpHuiA+7g= |
| X-Notice | Filtered by postfilter v. 0.9.2 |
| Xref | csiph.com tw.bbs.comp.lang.perl:28 |
Show key headers only | View raw
談到要把把錯誤狀態從函式中傳出來,基本上有兩種方式。有不少函式庫傾向使用
die,但把錯誤狀況作為傳回值的一部分的作法也很常見。
今天發現 Try::Tiny 在的傳回值很適合用來做個簡單的轉換器:
use Try::Tiny;
sub error_or_result (&) {
my ($f) = @_;
try {
undef, $f->()
} catch {
$_
}
}
用法:
my ($err, @ret) = error_or_result { foo() };
如果 foo() 執行途中以 die 傳錯誤出來,那麼 $err 內會裝有錯誤內容,而
@ret 則會是空的。如果沒有錯誤發生,那麼 $err 會是 undef,而 @ret 會裝有
foo() 的傳回值。
也就是它會把例外事件裝換成傳回值,如果慣例上你的程式碼內是使用傳回值來處
理錯誤狀態,那麼有這種轉換用的函式或許可以讓一些地方簡化一點。
----
Back to tw.bbs.comp.lang.perl | Previous | Next — Next in thread | Find similar
轉換錯誤處理慣例 Kang-min Liu <gugod@gugod.org> - 2022-09-12 18:50 +0900 Re: 轉換錯誤處理慣例 Kang-min Liu <gugod@gugod.org> - 2022-09-14 12:31 +0900
csiph-web