PHP5 exception processing mechanism [4] - PHP5 error processing - Return Error Flag (Error Tag)

xiaoxiao2021-03-06  74

(2) Return to the wrong mark

The error handling of the script hierarchy is relatively rough but it is useful. Despite this, we sometimes need greater flexibility. We can use the way to return to the wrong identifier to tell the customer code "Error happened!". This will be determined by handing the program to continue, how to continue to hand over the customer code.

Here we improve the previous example to return a script to perform an error (False is a commonly used nice choice).

INDEX3.PHP

cmddir} / {$ CMD} .php "; if (! file_exists ($ path)) {RETURN FALSE;} Require_once $ path; if (! Class_exists ($ cmd)) {Return False;} $ RET = New $ cmd (); if (! IS_A ($ RET, 'Command')) {RETURN FALSE;} RETURN $ RET;}}?>

This means that you can handle multiple errors according to the environment, and will stop the execution of the program immediately when the first error occurs.

getcommandObject ('realcommand'); if (is_bool ($ cmd)) {Die ("Error getting command / n");} Else {$ cmd-> EXECUTE ();}?>

or just a logged error:

getcommandObject ('realcommand'); if (is_bool ($ cmd)) {Error_Log ("Error getting command / n", 0) } Else {$ cmd-> execute ();}?>

The advantage of using the error flag like "false" is intuitive, but the amount of information given is not enough, we can't know which link is on display, resulting in returning false. You can set an error in the error, which outputs an error message after generating an error.

INDEX4.PHP

Error_Str = get_class ($ this). ": $ msg";} function error () {Return $ this-> error_str;} Function getcommandObject ($ cmd) {$ Path = "{$ THIS -> cmddir} / {$ cmd} .php "; if (! file_exists ($ path)) {$ this-> setError (__ function__," cannot Find $ PATH / N "); Return False;} Require_Once $ PATH; IF (! Class_exists ($ cmd)) {$ this-> setError (__ function__, "class $ cmd does not exist"); return false;} $ RET = New $ cmd (); if (! is_a ($ RET, 'Command ')) {$ This-> setError (__ function__, "$ cmd is not a command"); return false;} RETURN $ RET;}}?> This simple mechanism allows setError () records the error message. Other code can get information about script errors by error (). You should draw this feature and put it in a basic class, and other cates are inherited from this class. This can be uniformly handled errors, otherwise it may appear confusion. I have seen some programs in different classes using getErRorstr (), getError (), and error () and other functions.

However, in actual development, all classes in the program are difficult to inherit from the same classes, unless otherwise using the interface (Interface), some sub-class itself cannot be implemented, but that is already PHP5 content. Just as we will mention, PHP5 provides a better solution.

转载请注明原文地址:https://www.9cbs.com/read-121902.html

New Post(0)