PHP框架开发——swoole框架异常处理
这篇文章最后更新于1394天前,您需要注意相关的内容是否还可用,如有疑问请联系作者!
在swoole框架中使用 set_error_handler 和 set_exception_handler 根本不起作用,原因应该是被swoole扩展从底层劫持啦。当需要整体捕获运行中的错误和异常的时候,只能将绑定在onRequest的函数try.. catche 起来
另外 在php7中 Error和Exception都实现了 Throwable 接口,所以如何想要同时捕获 这两种错误应该 捕获Throwable
try { $this->kernal->process($this->request, $this->response); } catch (\Throwable $throwable) { //获取header $accept = $this->request->header["accept"]; if (strpos($accept, "json")) { $data["file"] = $throwable->getFile(); $data["codeLine"] = $throwable->getLine(); $data["error"] = $throwable->getMessage(); $this->response->setHeader("Content-Type", "application/json"); $this->response->send(json_encode($data)); } else { $str = <<<EOL <h1>Error Message: {$throwable->getMessage()}</h1> <h2>Error File: {$throwable->getFile()}</h2> <h2>Error Line: {$throwable->getLine()}</h2> <h3>Error Traces:</h3> EOL; foreach ($throwable->getTrace() as $trace){ $str .= "<h3>{$trace["file"]}:{$trace["line"]}</h3>"; } $this->response->send($str); } }
文章版权声明:除非注明,否则均为IT技术交流分享 IDC管理计费系统 私有云管理系统 PVE管理系统 私有云系统原创文章,转载或复制请以超链接形式并注明出处。