鍍金池/ 問(wèn)答/PHP/ 怎么把throw的錯(cuò)誤用json輸出

怎么把throw的錯(cuò)誤用json輸出

public function run(){

    try{

        $this->_setRequestMethod();

        $this->_setupResource();

        $this->runcontroller();

    }catch(Exception $e){

        $this->_json(['error'=>$e->getMessage()],$e->getCode());
    }

}

public function _setRequestMethod(){

    $this->_requestMethod=$_SERVER['REQUEST_METHOD'];

    if(!in_array($this->_requestMethod,$this->_allowRequestMethods)){
        throw new\Exception("請(qǐng)求方法不被允許", 405);

    }

}

public function _json($array,$code=0){

    if($array === null && $code === 0){

        $code = 204;

    }

    if($array !== null && $code === 0){

        $code = 200;

    }

    header("HTTP/1.1 ".$code."  ".$this->_statusCodes[$code]);

    header("Content-Type=application/json;charset=UTF-8 ");

    if($array !== null){

        echo  json_encode($array,JSON_UNESCAPED_UNICODE);

    }

    exit();

}

執(zhí)行run()的時(shí)候返回

Fatal error: Uncaught Exception: 請(qǐng)求方法不被允許 in /www/wwwroot/www.entercode.cn/api/Rest/restful.php:149 Stack trace: #0 /www/wwwroot/www.entercode.cn/api/Rest/restful.php(69): Restrestful->runcontroller() #1 /www/wwwroot/www.entercode.cn/api/index.php(20): Restrestful->run() #2 {main} thrown in /www/wwwroot/www.entercode.cn/api/Rest/restful.php on line 149

但是我想將返回的錯(cuò)誤結(jié)果
{error':'請(qǐng)求方法不被允許','405'}

是我哪里寫(xiě)錯(cuò)了嗎?

回答
編輯回答
赱丅呿
class Etest
{
    public function run()
    {
        try
        {
            $this->A();
            $this->B();
            $this->C();
        }
        catch(\Exception $e)
        {
            $this->_json(['error' => $e->getMessage(),'code' => $e->getCode()]);
        }
    }
    public function A()
    {

    }
    public function B()
    {
        throw new \Exception("Not Found!",404);
    }
    public function C()
    {

    }
    public function _json($aArray)
    {
        header("HTTP/1.1 ".$aArray['code']." ".$aArray['error']);
        header("Content-Type:application/json;charset=utf-8;");
        echo json_encode($aArray,JSON_UNESCAPED_UNICODE);
        exit;
    }
}
(new Etest)->run();

可以參考下 這樣寫(xiě)無(wú)報(bào)錯(cuò)
可以正常捕獲Exception
2017年8月13日 11:05