zoukankan      html  css  js  c++  java
  • PHP框架开发——swoole框架异常处理

    在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形式显示,(请忽略这个丑陋的样式)

  • 相关阅读:
    cocos2d-x 坐标系
    Linux 用户和用户组
    Linux 挂载分区 + swap 分区
    Linux 分区 磁盘分区与格式化
    Linux MBR分区(重点知识)
    Linux -磁盘管理 ip http://blog.csdn.net/xh16319/article/details/17272455
    Linux 底行模式常用命令
    Linux Bash 通配符
    Linux Bash 的基本功能 管道符
    Linux Bash的基本功能 输出重定向
  • 原文地址:https://www.cnblogs.com/itsuibi/p/13584648.html
Copyright © 2011-2022 走看看