What are Exceptions and how should I create and embed them in PHP

Asked

Viewed 435 times

11

I’m creating an MVC system and I want to implement Exceptions in my system. I’ve just never particularly used it. So I wanted to know how to apply the Exceptions, since I saw here in Stackoverflow in Portuguese someone talking (I don’t remember if in response or comment) that most people don’t know how to use the Exceptions correctly. So I saw myself in this group of people who don’t know how to use Exceptions, or at least I never gave much importance to them, but now I saw a real need to use them.

How I’m developing a code that will be the basis for several projects my future, both academically and even professionally, I need to standardize and develop it in a way that really makes the development of some project something more "simple" or focused and that facilitates and does not hinder.

As Exceptions go down in history to help in the debug, I want the framework give me the trace of the error, from where it started to where it left off. I need to know the reasons for the errors and also that they tell me how to correct them. And since I’m new to object-oriented programming, this is the first time I’ve seen myself creating Exceptions and not treating them. But enough of history, let’s go to the code.

I’ve already created a Exception, code:

<?php
namespace Core\Exception;
use \Exception;

class SystemException extends Exception {
   function __construct($code, $args = array(), Exception $previous = NULL ) {
      $language = (require BASE . 'language' . DS . LANG . DS . 'exceptions.php');
      $format = $language[$code];

      $message = vsprintf($format, $args);
      parent::__construct($message, $code, $previous);
   }
   // personaliza a apresentação do objeto como string
   // public function __toString() {
   //    return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
   // }
}

So my idea was to create this SystemException to log bugs and all the others to be extended from it, or something like that. (So far I don’t know if this will work). Note that I also modified the type of builder, in fact I do not know if this is a good practice, the idea is to facilitate the translation of the errors. But I don’t know if I should leave it to the "system" that is developed instead of giving that responsibility to the framework.

And here a way where I’m casting the exception:

protected function register($params){
   if (empty($params['controller']))
      throw new SystemException(Exceptions::E_INVALIDPARAMETERVALUE, ['NULL', '$params[controller]']);
   if (empty($params['action']))
      throw new SystemException(Exceptions::E_INVALIDPARAMETERVALUE, ['NULL', '$params[action]']);
   if (empty($params['lang'])){
      $params['lang'] = (empty($_COOKIE['language']) ? LANG : $_COOKIE['language']);
      throw new SystemException(Exceptions::E_INVALIDPARAMETERVALUE, ['NULL', '$params[controller]']);
   }

}

When I am releasing an exception I am only creating it by informing a code, which searches the messages in a language file and step as parameters in a array data used in the message.

So I was wondering if I understood the concept and I’m applying the exceptions correctly?

So there are some points/questions about the creation and concept of Exceptions:

  • How to standardize exceptions?
  • How to register logs of the exceptions made, automatically?
  • What is the application of parameter previous in the PHP exception?
  • Good practice and bad practice on Exceptions?

Obs.: The automaticity of the records of logs would be the idea of a class "father" register logs every time an exception is thrown from a class that inherits from it.

  • 2

    Some people said that people don’t know how to use Exceptions correctly? Who will be :P I don’t know if I would have a specific answer for PHP, but there is already a lot about it in the tag: http://answall.com/questions/tagged/exce%C3%A7%C3%A3o and especially in my answers to the tag: http://answall.com/search?q=user%3A101+%5Bexception%5D I talk about everything that is asked, although some things are for other languages. I don’t know if I can put something new beyond what I’ve already posted. It’s an almost identical resource in all languages. What can I write?

  • @bigown will take a look at any content if I see that already answered everything I mark as duplicate or delete I know there, else I warn you...

  • 1

    @bigown has a lot of specific stuff in C#, I wanted specifically for PHP, I’ll put a Exception that I have already created in the question and maybe give a reformulated her not to be so wide.

  • @bigown gave a repaginada in the question... I do not know if improved much... : P

  • 1

    There might be some specific things in there that I won’t risk.

2 answers

3

I can help you with the question: How could I standardize my exceptions and log logs of automatically released exceptions?

If I understand correctly, you would like to release a log when the released exception was coming from the instance of SystemException.

I believe the function set_exception_handler can help you in this case. See:

set_exception_handler(function($exception)
{
      if ($exception instanceof SystemException) {
          file_put_contents('log.txt', (string)$exception, FILE_APPEND);
      }

     throw $e; // Outras exceções são tratadas de maneira padrão
});

In the case of your method code Core\Route::register, I think it was very generic to use the exception SystemException.

I believe that a more elegant approach would be to create another class of exceptions, which inherits SystemException, to refer only to exceptions that may occur in the Route,

class RouteException extends SystemException
{}

Another fact is that, because it is also about the treatment of arguments, I would use exceptions such as UnexpectedValueException or InvalidArgumentException. If so, you could also create an heiress exception of SystemException (you want to use for log) that was specific to inform the invalidity of arguments.

I say this because PHP treats the two expressions as TRUE, on account of the inheritance:

$e = new SystemException;

$re = new RouteException;

$e = instanceof SystemException; // True

$re instanceof RouteException; // True
  • I will improve the information of the question

  • Beauty Wallace, it’s in that sense. The intention really is to create other Exceptions as the example you gave RouteException.

  • The idea of treating exceptions, is nothing more than you respond to each numerical error output, a reply message that is interesting to the user. I honestly don’t see the need for this, since a framework already has this implemented internally, just use some translation package.

  • What if the guy doesn’t use framework? He’ll have to do in hand :)

2

Here is an example of good practice for treating exceptions, because in addition to creating a componentization and documenting your system, it allows no one below to destroy its functioning:

namespace SuaClasse\Component {

    interface Exception
    {}

    class UnexpectedValueException 
          extends \UnexpectedValueException 
          implements Exception
    {}

    class ReportingExpection
    {
        public static function doSomething()
        {
           try {
                if ($somethingExceptionalHappens) {
                    throw new UnexpectedValueException('mensagem da exceção');
                }

           } catch (UnexpectedValueException $e) {
              error_log($e->getMessage(), 3, "/var/tmp/errors.log");
           } 
        }
    }

}

Now that you have your component, just use it:

SuaClasse\Component\ReportingExpection::doSomething();
  • I saw the code, but I could explain better what it does and why it’s good practice?

  • Look at this article explains in detail: http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3

  • 1

    Zend Framework 2.0 follows this line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.