Showing posts with label error. Show all posts
Showing posts with label error. Show all posts

Thursday, April 7, 2016

PHP Errors and Exception handling

When learning  PHP is very important to find the correct source of information.

I found a very good article on the topic "PHP Error handling" that  worth being shared:

http://alanstorm.com/php_error_reporting

So in PHP there are 2 systems, one for Error handling, and one for Exceptions.

Errors are real errors from PHP code, like missing  ";" at the end of  statement or trying to access an undefined variable.

Exceptions are some objects crafted by programmers. You could check if a variable has  a value bigger than 10, and if not you can throw an Exception with a message describing why  this makes no sense in your application logic.

There is also a difference in that Error handling is old school and Exceptions are OOP. You can create your own Exception class to match your needs: http://php.net/manual/en/language.exceptions.extending.php

Roughly speaking, errors are a legacy in PHP, while exceptions are the modern way to treat errors. The simplest thing then, is to set up an error-handler, that throws an exception. That way all errors are converted to exceptions, and then you can simply deal with one error-handling scheme. The following code will convert errors to exceptions for you:

function exceptions_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
set_error_handler('exceptions_error_handler');
error_reporting(E_ALL ^ E_STRICT);

Text from http://stackoverflow.com/questions/134331/error-handling-in-php

This answer from Stackoverflow pretty much clarifies how things work now, you set an error handler function and in that function you throw an Exception. You make sure to catch that Exception in your code because otherwise you will get a Uncaught Fatal Error.

Errors and exceptions in Symfony

The Debug componenet from Symfony works on the same principle:
The ErrorHandler class catches PHP errors and converts them to exceptions (of class ErrorException or FatalErrorException for PHP fatal errors)
 From Symfony doc: http://symfony.com/doc/current/components/debug/introduction.html

In the development environment, Symfony catches all the exceptions and displays a special exception page with lots of debug information to help you quickly discover the root problem.

Since these pages contain a lot of sensitive internal information, Symfony won't display them in the production environment. Instead, it'll show a simple and generic error page.

Information on how to override these error pages can be found in the Symfony documentation here: http://symfony.com/doc/2.8/cookbook/controller/error_pages.html