4

In PHP, if a value is considered "unknown" (not per se invalid) should this raise a logic or runtime exception?

<?php
function foo($bar) {
    // logic
    if(!is_string($bar)) {
        throw new \InvalidArgumentException('invalid *argument*');
    }
    if(strlen($bar) < 4) {
        throw new \DomainException('invalid *bar*');
    }
    static $knownBars = array('bar1', 'bar2');
    if(!in_array($knownBars)) {
        throw new \DomainException('unknown *bar*');
        //throw new \UnexpectedValueException('unknown *bar*');
    }

    // runtime
    $bar;
}

The first 2 exceptions are obvious, however the last one remains a bit unclear to me. Both seem to make sense; a logic/domain error as we expect one of a defined data-set, a runtime/unexpected value error as we actually got a unexpected value.

Which one should i throw?

Also what if the logic part is a single setter method and we want to replace the static array (data-set) with a database lookup instead... Is it OK to expect runtime exceptions in logic code due database failure, etc? Or should we move the database lookup to the runtime code and still throw a logic exception if "bar" is considered unknown?

4

2 に答える 2

12

論理例外は、コンパイル時に発生するエラー用です。これが意味する意味で PHP にはコンパイル時間がないため、通常は「開発中に発生したエラー」(開発者が依存関係などを渡すのを忘れた場合など) として解釈されますが、ランタイム例外は予期しないエラー (通常はユーザーに起因するもの) 用です。入力) コードが実行されるとき。

しかし、率直に言って、Spl Exception 階層全体が Fubar です。したがって、必要なものを使用するか、独自のものを作成してください。

https://wiki.php.net/rfc/spl-improvements/exceptionsも参照してください。

于 2013-01-05T12:38:29.710 に答える
0

データセットが静的であるため(したがってチェックインされているため)、これにはドメインを使用します...データsetFoo()セットunexpectedvalueが動的である(したがってチェックインされているdoSomethingWithFoo())場合に使用します。

于 2013-01-05T13:28:04.003 に答える