0

I'm creating some re-usable functions, and right now I have error handling setup like this:

<?php
...
public function insertAfter( $index, $objects )
{
    if ( ! is_int( $index ) ) {
        trigger_error( 'Cursor::insertAfter() expects parameter 1 to be integer, ' . gettype( $index ) . ' given', E_USER_WARNING );
    } else {
        // Do my regular code
    }

    return $this;
}
...

I tried setting it up to work just like PHP would handle an error. Is this an appropriate way to do things?

Brandon
  • 16,382
  • 12
  • 55
  • 88

2 Answers2

4

You may throws an exception. Take a look at Exception in PHP manual.

EDIT: Here are some useful SO threads.

  1. PHP Error handling: die() Vs trigger_error() Vs throw Exception.
  2. In PHP5, should I use Exceptions or trigger_error/set_error_handler?.
  3. trigger_error vs. throwing exceptions
Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • I had that originally, but I prefer not to litter my code with try catch statements – Brandon Dec 09 '11 at 03:51
  • 2
    An [`InvalidArgumentException`](http://www.php.net/invalidargumentexception) would be most appropriate. – deceze Dec 09 '11 at 03:51
  • 1
    @Rogue You don't have to catch exceptions like this, that's the point. Passing an *invalid* argument type is not something that should be *caught*, it's an *exceptional mistake* that should stop your program and lead you to fix your code. – deceze Dec 09 '11 at 03:52
  • 1
    @deceze Thanks for point out [`InvalidArgumentException`](http://ca3.php.net/invalidargumentexception), this is exactly what I was looking for. Also, thank you for clarifying exceptions. – Brandon Dec 09 '11 at 03:59
0

Check out the Altumo package. It has quite a few handy validators that do what you are looking to do.

For example,

$index = \Altumo\Validation\Numerics::assertInteger( 
    $index, 
    'Cursor::insertAfter() expects parameter 1 to be integer, ' . gettype( $index ) . ' given'
);

There are validators for Object types, strings, boolean, etc.

P.S. Exceptions are more flexible than trigger_error() because you can control them more granularly. Here's a good thread on that topic.

Community
  • 1
  • 1
0x6A75616E
  • 4,696
  • 2
  • 33
  • 57