0

I'm trying to find right solution to catch messages but not sure if this is possible or no.

I have a simple PHP structure with try and catch:

if (!$this->issetAndNotEmpty($id))
                    {
                        throw new Exception('My error message');
                    }

...
  catch (Exception $exc)
  {
        echo'<div class="error">'.  $exc->getMessage().'</div>';
  }
...

It works as supposed. But we have a requirement to return error noise(beep) on some errors (but not on all of them). Best way to do this is add new function into catch section. In this way it beeps every time. Is it possible to add second parameter into throw new Exception('My error message', true(or something like that)); and then run this function under if statement? Another way is to add variable inside class and set to true and check it inside catch before error message.

Is it possible to do that in first way?

1
  • It's generally considered bad practice to throw just generic exceptions. You should use a more specific one (PHP built-in ones like \InvalidArgumetException if possible, your own exceptions that extend Exception if not). You can then take different error paths dependant on the type of exception thrown. You can also give a new exception a code as well as a message. Changing behaviour depending on the text content of the exception message is definitely not recommended Commented Sep 26, 2018 at 9:45

1 Answer 1

1

You should create a specific Exception class that extends PHP's generic Exception that can take extra parameters, and will allow you to catch it specifically and handle as needed, allowing other exceptions to fall through to the default catch.

<?php

/**
 * Class BeepException
 * Exception that beeps
 */
class BeepException extends Exception
{
    // Member variable to hold our beep flag
    protected $beep;

    /**
     * BeepException constructor.
     * @param $message
     * @param bool $beep
     * @param int $code
     */
    public function __construct($message, $beep=false, $code = 0)
    {
        $this->beep = $beep;

        parent::__construct($message, $code);
    }

    /**
     * Return the value of our beep variable
     * @return bool
     */
    public function getBeep()
    {
        return $this->beep;
    }
}

try
{
    throw new BeepException('This should beep...', true);
}
catch(BeepException $e)
{
    echo $e->getMessage().PHP_EOL;

    if($e->getBeep())
    {
        echo 'BEEEEEEP!'.PHP_EOL;
    }
}
catch(Exception $e)
{
    echo $e->getMessage().PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

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.