PHP exception arguments

I am working on a PHP library that can be used in different environments by different PHP projects, and I try to be as minimal as possible.

In some cases, I must, for example, throw exceptions.

throw Exception('template has invalid tag');

A similar error is not very useful without a tag name:

throw Exception('template has invalid tag: '.$tag);

This would be difficult to localize and could lead to any kind of injection.

QUESTION: What is the best way to pass extra variables with Exception to PHP?

(note: my library is building SQL Query, and I would prefer it to focus on the task rather than solving problems with exceptions)

+4
source share
3 answers

. Exception ( \Exception , ) .

, , . . . , , . .

, :

class InvalidTagException extends \Exception
{
    protected $tag;

    public function __construct($message, $tag, $code = 0, Throwable $previous = NULL)
    {
        // Let the parent class initialize its members
        parent::__construct($message, $code, $previous);
        // Initialize own members
        $this->tag = $tag;
    }

    public function getTag()
    {
        return $tag;
    }
}

// Declare other Exception classes in a similar fashion, for each kind of exception you throw
class InvalidValueException extends \Exception
{
    // ...
}

, :

try {
    // call your library code here
} catch (InvalidTagException $e) {
    // Handle in application specific way

} catch (InvalidValueException $e) {
    // A different type of exception requires a different type of handling
}
+4

.

:

class AnswerException extends \Exception
{
    protected $group;
    public function __construct($message = "",  $group = null, $code = 0, \Exception $previous = null){
        $this->group = $group;
        return parent::__construct($message, $code, $previous);
    }
    public function getGroup(){
        return $this->group;
    }
}

, :

throw new AnswerException('template has invalid tag',$tag);

AnswerException $exception->getGroup().

+3

One possible solution is to use sprintfas follows:

throw new Exception(sprintf(_('template has invalid tag %s'), $tag));

where _()is your localization function.

But this is not the best solution, because it is still open for html injections and becomes rather messy when you have 5 variables. As far as I know, Wordpress uses this approach to localization.

+1
source

All Articles