mysql 抛出自定义异常处理_ThinkPHP5自定义抛出异常

2372.html

建立 application 下建立common/exception目录.

新建ExceptionHandler.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

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'];

}

}

}

在模块目录下或全局config.php里修改:

'default_return_type' => 'json',

// 异常处理 handle 类 留空使用 \think\exception\Handle

'exception_handle' => 'app\common\exception\ExceptionHandler',

这样用 THINKPHP5 写 API 报错就不会返回 html 页面拉..返回是 json 格式.

~谢谢打赏~

c6d2925bbe17d2dbf6ec9e744fd33b57.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值