为了账号安全,请及时绑定邮箱和手机立即绑定

怎么把throw的错误用json输出

怎么把throw的错误用json输出

PHP
qq_花开花谢_0 2019-03-15 11:34:11
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("请求方法不被允许", 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(); } 执行run()的时候返回 Fatal error: Uncaught Exception: 请求方法不被允许 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 但是我想将返回的错误结果{error':'请求方法不被允许','405'} 是我哪里写错了吗?
查看完整描述

1 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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();

可以参考下 这样写无报错
可以正常捕获Exception
查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 480 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信