TP5异常处理

TP5异常处理

标签(空格分隔): php, thinkphp5

自定义异常处理

1458583-20190530163500063-57406764.png

namespace app\common\exception;
use think\Exception;

class ApiException extends Exception
{
    public $code = 0;
    public $message = 'invalid parameters';
    
    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'];
    }
}

异常处理接管[重写]

1458583-20190530163547425-986932368.jpg

1458583-20190530163509684-1184332670.png

1458583-20190530163523054-1200643681.jpg

1458583-20190530163530067-2120413347.jpg

1458583-20190530163553588-851801741.jpg

<?php
/**
 * Created by PhpStorm.
 * User: ywf
 * Date: 2019/5/16
 * Time: 11:13
 */
namespace app\common\exception;
use think\Log;

class MyHttpException extends \think\exception\Handle
{
    public function render(\Exception $e)
    {
        if (config('app_debug')) return parent::render($e);

        if ($e instanceof ApiException) {
            return json([
                'code' => $e->code,
                'msg' => $e->message,
            ]);
        }

        $this->recordErrorLog($e);
        return json([
            'code' => 500,
            'msg'  => $e->getMessage() ? : 'sorry server internal error!',
            'file' => $e->getFile(),
            'line' => $e->getLine(),
        ]);
    }

    /**
     * 记录异常日志
     * @param \Exception $e
     */
    private function recordErrorLog(\Exception $e)
    {
        Log::record($e->getMessage(), 'error');
        Log::record($e->getFile() . ' : ' . $e->getLine() . '行', 'error');
        Log::record($e->getTraceAsString(), 'error');
    }

}

转载于:https://www.cnblogs.com/yanweifeng/p/10950424.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值