重写Handle的render方法,实现自定义异常消息-----------------------------------------------------------------------
首先要在config.php里面配置
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '\\app\\common\\exception\\ExceptionHandler', ExceptionHandler.php

<?php

namespace app\common\exception;

use think\exception\Handle;
use think\Log;
use Exception; /**
* 重写Handle的render方法,实现自定义异常消息
* Class ExceptionHandler
* @package app\common\library\exception
*/
class ExceptionHandler extends Handle
{
private $code;
private $message; /**
* 输出异常信息
* @param Exception $e
* @return \think\Response|\think\response\Json
*/
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 app\common\exception;

use think\Exception;

/**
* 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'];
}
}
}

抛出异常时显示如下


 

最新文章

  1. Linux记录从此开始
  2. NPOI MVC 模型导出Excel通用类
  3. 转&lt;%%&gt;、&lt;%=%&gt;、&lt;%$%&gt;、&lt;%@%&gt;的区别
  4. Kafka消息保证不丢失和重复消费问题
  5. [DevExpress]ChartControl之创建X,Y轴Title示例
  6. Linux一键安装PHP/JAVA环境OneinStack
  7. Directx 3D编程实例:绘制可变速旋转的三角形
  8. 【转】生产环境MySQL Server核心参数的配置
  9. poj3613(恰经过N条边的最短路)
  10. Ruby入门--Linux/Windows下的安装、代码开发及Rails实战
  11. css设置层级显示
  12. SpringBoot中使用Servlet,Filter,Listener
  13. jvm学习笔记一(垃圾回收算法)
  14. mycat 单库多表实现水平分片
  15. (转)IIS7无法读取配置文件解决办法
  16. 1.1.15 word调整文字与下划线之间的间距
  17. Zabbix系列之三——部署JMX监控tomcat
  18. Latex 算法过长 分页显示方法
  19. 在windows上通过ssh远程链接linux服务器[转]
  20. unity缓动插件DOTween Pro v0.9.680

热门文章

  1. CDQ分治的嵌套
  2. selenium的方法
  3. python 二叉搜索树相关代码
  4. Eratos筛法(筛选素数)
  5. git status: HEAD detached from origin/master问题的解决
  6. 【Spark机器学习速成宝典】推荐引擎——协同过滤
  7. Linux字符编码默认为UTF-8,如出现乱码可设置为GBK
  8. 【译】优雅的停止docker容器
  9. centos7最小安装怎么安装防火墙
  10. SVN错误信息汇总