exception handling - PHP: What's the best practice for catching PHP errors? -


some php core function don't throw exception issue error instead. in cases need 'catch' error in order know @ runtime if error occured.

concrete use case: check if pattern valid regex preg_* functions (see this related question, not mine though)

i know it's possible use set_error_handler set custom error handler throws exceptions (example). avoid setting my error handler globally, since i'm working on library , not want change phps default behaviour.

my current 'workaround' set error handler before calling preg_*, wrap in try/catch block , reset error handler afterwards:

    $ex = null;     $pattern = "invalid";     $subject = "doesn't matter";     try{         set_error_handler('my_error_handler_func'));         preg_match($this->pattern, $subject);     }catch(\exception $e){         $ex = $e; // invalid pattern     }     //finally     restore_error_handler();     if($ex !== null){         throw $e;     } 

my preferred solution set error handler specific namespace, does not seem possible. i'm wondering if there's more elegant solution general problem.

i wrap execution of core function custom function throws exception in case of error, this:

function my_fun() {     if(@preg_match($this->pattern, $subject) === false) {         $error = error_get_last();         if(is_null($error)) {             $msg = 'unknown problem';         } else {             $msg = $error['message'];         }         throw new exception($msg);     } } 

note i'm using error_get_last() obtain original error message preg_match() , use exception message.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -