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

  • 相关阅读:
    数据库(2019年10月30日)
    (面试题)反射(2019年10月28日)
    反射(2019年10月28日)
    常微分复习重点
    重要定理及其证明
    实变函数复习重点
    泛函分析重点定理
    自旋玻璃简介
    Fnight博文发布规范
    [分析力学]解题思路
  • 原文地址:https://www.cnblogs.com/itsuibi/p/13584648.html
Copyright © 2011-2022 走看看