简体   繁体   English

有两个参数的PHP异常

[英]PHP Exception with two parameters

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 : 我有一个简单的PHP结构,可以使用trycatch

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. 最好的方法是在catch部分添加新功能。 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)); 是否可以添加第二个参数以throw new Exception('My error message', true(or something like that)); and then run this function under if statement? 然后在if语句下运行此功能? Another way is to add variable inside class and set to true and check it inside catch before error message. 另一种方法是在类内部添加变量并将其设置为true ,然后在错误消息之前在catch进行检查。

Is it possible to do that in first way? 有可能以第一方式做到这一点吗?

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. 您应该创建一个特定的Exception类,以扩展PHP的通用Exception ,该类可以接受额外的参数,并允许您专门捕获它并根据需要进行处理,从而允许其他异常进入默认捕获。

<?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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM