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

  • 相关阅读:
    专职DBA-MySQL体系结构与基本管理
    JSON
    MIME类型
    文件上传下载
    response常用的方法
    2020.11.27小记
    HTTP请求状态码
    1561. Maximum Number of Coins You Can Get
    1558. Minimum Numbers of Function Calls to Make Target Array
    1557. Minimum Number of Vertices to Reach All Nodes
  • 原文地址:https://www.cnblogs.com/itsuibi/p/13584648.html
Copyright © 2020-2023  润新知