swoole框架异常处理

2020-09-01 11:10:14 浏览数 (1)

在swoole框架中使用 set_error_handler 和 set_exception_handler 根本不起作用,原因应该是被swoole扩展从底层劫持啦。当需要整体捕获运行中的错误和异常的时候,只能将绑定在onRequest的函数try.. catche 起来

另外 在php7中 Error和Exception都实现了 Throwable 接口,所以如何想要同时捕获 这两种错误应该 捕获Throwable

代码语言:javascript复制
 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形式显示,(请忽略这个丑陋的样式)

0 人点赞