在swoole框架中使用 set_error_handler 和 set_exception_handler 根本不起作用,原因應該是被swoole擴展從底層劫持啦。當需要整體捕獲運行中的錯誤和異常的時候,只能將綁定在onRequest的函數try.. catche 起來
另外 在php7中 Error和Exception都實現了 Throwable 接口,所以如何想要同時捕獲 這兩種錯誤應該 捕獲Throwable
1 try { 2 $this->kernal->process($this->request, $this->response); 3 } catch (\Throwable $throwable) { 4 //獲取header 5 $accept = $this->request->header["accept"]; 6 7 if (strpos($accept, "json")) { 8 $data["file"] = $throwable->getFile(); 9 $data["codeLine"] = $throwable->getLine(); 10 $data["error"] = $throwable->getMessage(); 11 $this->response->setHeader("Content-Type", "application/json"); 12 $this->response->send(json_encode($data)); 13 } else { 14 $str = <<<EOL 15 <h1>Error Message: {$throwable->getMessage()}</h1> 16 <h2>Error File: {$throwable->getFile()}</h2> 17 <h2>Error Line: {$throwable->getLine()}</h2> 18 <h3>Error Traces:</h3> 19 EOL; 20 foreach ($throwable->getTrace() as $trace){ 21 $str .= "<h3>{$trace["file"]}:{$trace["line"]}</h3>"; 22 } 23 $this->response->send($str); 24 } 25 26 }
接口訪問出錯時,以json格式顯示

頁面訪問時以web形式顯示,(請忽略這個丑陋的樣式)

