Return JSON 来自在构造函数 Codeigniter 3 中调用的方法的响应

Return JSON response from method called in constructor Codeigniter 3

我正在 Codeigniter 3 中构建自定义 Auth 系统。

鉴于此代码:

class Base_REST extends REST_Controller
{
    protected $user;

    public function __construct($config = 'rest')
    {
        parent::__construct($config);

        $this->load->helper('url');
        $this->load->library('Oauth');

        $this->user = $this->initUser();
    }

    /**
     * @return mixed
     */
    private function initUser()
    {
        try {
            return $this->oauth->checkBearerToken($this->head('Authorization'));
        } catch (Exception $exception) {
            // ???
        }
    }
}

抛出异常时,我不能 return JSON 像这样:

{
 "message": "The token is not valid"
}

我正在尝试这个,因为我 return JSON 来自 Controllers:

catch (Exception $exception) {
   $this->response((object) [ 'message' => $exception->getMessage()], $exception->getCode());
}

但它在响应正文中什么也没显示。

有人知道如何处理和 return 这些错误吗?我已经看到了 echo 的使用,但我认为这不是最好的方法,因为如果在我的代码执行过程中出现任何错误,响应主体包括 echo 但也包括错误。

提前致谢!

代码是否直接在return之后退出,header内容是否设置为json?

codeigniter 文档中的示例:

$response = array('status' => 'OK');

$this->output
    ->set_status_header(200)
    ->set_content_type('application/json', 'utf-8')
    ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
    ->_display();
exit;