zoukankan      html  css  js  c++  java
  • TP5实现自定义抛出异常消息(关闭debug)

    重写Handle的render方法,实现自定义异常消息-----------------------------------------------------------------------
    首先要在config.php里面配置

    // 异常处理handle类 留空使用 	hinkexceptionHandle
    'exception_handle' => '\app\common\exception\ExceptionHandler',



    ExceptionHandler
    .php


    <?php

    namespace appcommonexception;

    use thinkexceptionHandle;
    use thinkLog;
    use Exception;

    /**
    * 重写Handle的render方法,实现自定义异常消息
    * Class ExceptionHandler
    * @package appcommonlibraryexception
    */
    class ExceptionHandler extends Handle
    {
    private $code;
    private $message;

    /**
    * 输出异常信息
    * @param Exception $e
    * @return hinkResponse| hink esponseJson
    */
    public function render(Exception $e)
    {
    if ($e instanceof BaseException) {
    $this->code = $e->code;
    $this->message = $e->message;
    } else {
    if (config('app_debug')) {
    return parent::render($e);
    }
    $this->code = 0;
    $this->message = $e->getMessage() ?: '很抱歉,服务器内部错误';
    $this->recordErrorLog($e);
    }
    return json(['msg' => $this->message, 'code' => $this->code]);
    }

    /**
    * 将异常写入日志
    * @param Exception $e
    */
    private function recordErrorLog(Exception $e)
    {
    Log::record($e->getMessage(), 'error');
    Log::record($e->getTraceAsString(), 'error');
    }
    }


    自定义异常类的基类---------------------------------------------------------------------------------------------
     
    BaseException.php
    
    
    <?php

    namespace appcommonexception;

    use thinkException;

    /**
    * Class BaseException
    * 自定义异常类的基类
    */
    class BaseException extends Exception
    {
    public $code = 0;
    public $message = 'invalid parameters';

    /**
    * 构造函数,接收一个关联数组
    * @param array $params 关联数组只应包含code、msg,且不应该是空值
    */
    public function __construct($params = [])
    {
    if (!is_array($params)) {
    return;
    }
    if (array_key_exists('code', $params)) {
    $this->code = $params['code'];
    }
    if (array_key_exists('msg', $params)) {
    $this->message = $params['msg'];
    }
    }
    }





    抛出异常时显示如下

    
    
    
     
  • 相关阅读:
    表单制作注意事项
    【学习笔记】SIFT尺度不变特征 (配合UCF-CRCV课程视频)
    【图片匹配】--- SIFT_Opencv3.1.0_C++_ubuntu
    【LeetCode】297. Serialize and Deserialize Binary Tree
    【LeetCode】树的遍历
    【LeetCode 33】Search in Rotated Sorted Array
    ubuntu14.04 + GTX980ti + cuda 8.0 ---Opencv3.1.0(基础+opecv_contrib)配置
    [完美方案+无懈可击]ubuntu 14.04(LTS) + GTX 980Ti显卡配置
    OpenCV2.4.9 + Ubuntu15.04配置
    每天学点linux命令之locate 与 find 命令
  • 原文地址:https://www.cnblogs.com/zhyphp/p/11557708.html
Copyright © 2011-2022 走看看