tags:

views:

32

answers:

2

Is it possible to add an extra parameter when trowing an exception?

When i trow an exception I send along the error message but i would also like to send along the name of the field in a extra parameter. Something like

throw new Exception('this is an error message', 'the field');

So when i display the message i can do something like this

show_error($e->getFieldname, $e->getMessage());
+3  A: 

No, you would have to subclass Exception with your own implementation and add that method.

class FieldException extends Exception
{
    protected $_field;
    public function __construct($message="", $code=0 , Exception $previous=NULL, $field = NULL)
    {
        $this->_field = $field;
        parent::__construct($message, $code, $previous);
    }
    public function getField()
    {
        return $this->_field;
    }
}

But actually, I am not a friend of adding methods or properties to Exceptions. An Exception represents just that: something exceptional that happened in your application. The "field" property is really not part of the Exception, but part of the exception message, so I'd probably use a proper message like:

Wrong value for field foo. Excepted string, got integer

Gordon
how do i use it? if i do throw new FieldException('message', 'field'); i get Wrong parameters for Exception
Dazz
@Dazz `new FieldMessage('message',0,NULL,'field')`. The constructor for exceptions requires the message, but also allows for two optional arguments. Changing the order might break exception handling in complex applications where exceptions are rethrown, so to make sure nothing breaks, you add your param as the fourth (if you use that solution at all)
Gordon
I had to leave out the Exception $previous part, thats only for php 5.3.0+ and i using 5.2.9. and in the construct $this->field should be $this->_field. Then it works perfect! Tnx
Dazz
@Dazz good catches! Actually, thinking of it, I am not that sure swapping the argument order will do harm at all. ErrorException has different order too, but all the SplExceptions follow the regular Exception arguments order. You might just as well try. I still think a proper message would be the best option though :)
Gordon
A: 

You can implement your own Exception class, and customize it.

See Extending Exceptions article for details.

Kel