PHP - Converting all Errors to Exceptions - Good o

2019-04-03 23:41发布

I was wondering if it's considered a bad practice to globally convert all PHP Errors to Exceptions. Something like the following would be used:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    return false;
}

I suppose the assumption is that you can just start using "try/catch" around certain pieces of code that would normally throw Errors.

If it's not a case of Good/Bad, what are some of the Gotchas that could arise from this practice?

3条回答
再贱就再见
2楼-- · 2019-04-03 23:56

Use exceptions for things that are truly beyond your control.

Good:

try {
   if (fopen('file.txt', 'w') === false) {
      throw new Exception('File could not be opened for write access.');
   }
} catch (Exception $e) {
   echo $e->getMessage();
}

Bad:

try {
   if (strlen($_POST['username']) < 5) {
      throw new Exception('Username too short');
   }
} catch (Exception $e) {
   echo $e->getMessage();
}

The first way is good because it occurs when its something that the user or the application cant control. It cant open the file because? could be many reasons.

The second way is an overkill use of try /catch when you should use trigger_error. The second way is down to the user not knowing the rules of the username validation.

In short use exceptions when you cant control what your testing. Remember exceptions have more overhead then trigger_error aswell :)

查看更多
迷人小祖宗
3楼-- · 2019-04-03 23:57

having worked many years in Java/.Net in the past and now php in recent years, it's really annoying to have all these various error conventions, while the Exceptions Pattern is really good for everything - starting from application level errors, class errors, to system errors - anything.

I really invest quite a lot of work in trying to manage all sort of errors types, because each library/functions handles errors differently.

查看更多
The star\"
4楼-- · 2019-04-04 00:02

Unfortunately, this won't work on fatal/parse/etc. errors...

Don't remember exactly, but I've tried this and in some cases got a message like "can't throw exception without workaround..." but I can't remember the conditions to get this result. But now I use this way and completely satisfied.

查看更多
登录 后发表回答