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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

I had that originally, but I prefer not to litter my code with try catch statements
An InvalidArgumentException would be most appropriate.
@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 Thanks for point out InvalidArgumentException, this is exactly what I was looking for. Also, thank you for clarifying exceptions.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.