ThinkPhp6利用Sentry自动捕获异常

ThinkPhp6利用Sentry自动捕获异常

背景

  1. 利用Sentry1.11自动捕获ThinkPhp6的异常。

问题

  1. 以前使用ThinkPhp5.1时在public中的index.php入口文件写入sentry的自动捕获异常代码即可自动捕获异常,代码如下:
$sentry = require __DIR__ . '/../config/sentry.php';
if(!empty($sentry['core_key'])) {
    $client = new \Raven_Client($sentry['core_key']);
    $error_handler = new \Raven_ErrorHandler($client);
    $error_handler->registerExceptionHandler();
    $error_handler->registerErrorHandler();
    $error_handler->registerShutdownFunction();
}
  1. 目前使用ThinkPhp6写入对应代码无法自动捕获,具体原因还未找到,欢迎大家评论发言。

解决方案

  1. TP6.0框架手册后发现异常类默认托管在app/provider.php中,如图:TP6异常托管类
  2. 在ExceptionHandle中,手动添加Sentry报错,如下代码:
<?php
namespace app;

use app\common\utils\SentryLog;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息(日志)的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息(包括日志或者其它方式记录)
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // sentry error for http
        SentryLog::error(config('sentry.core_key'), self::_getErrorMsgData($e, 'http'));
        // 其他错误交给系统处理
        return parent::render($request, $e);
    }

    /**
     * @access public
     * @param  Output $output
     * @param Throwable $e
     */
    public function renderForConsole(Output $output, Throwable $e): void
    {
        // sentry error for console
        SentryLog::error(config('sentry.core_key'), self::_getErrorMsgData($e, 'console'));

        parent::renderForConsole($output, $e);
    }

    /**
     * 组装错误数据
     * @param Throwable $e
     * @param $render
     * @return false|string
     */
    private static function _getErrorMsgData(Throwable $e, $render)
    {
        $exception = [
            'error' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'render' => $render,
            'code' => $e->getCode(),
            'time' => date('YmdHis')
        ];
        return json_encode($exception, 256|JSON_UNESCAPED_SLASHES);
    }
}

  1. 以上代码中render方法主要捕获Http异常,renderForConsole主要捕捉Console错误,为全面捕捉,固两个方法都进行重写。
  2. 以上代码中SentryLog方法为自己进行封装,代码如下:
<?php
declare (strict_types = 1);

namespace app\common\utils;

/**
 * 预警
 * Class SentryLog
 * @package app\common\utils
 */
class SentryLog
{

    public function __construct($key)
    {
        $this->client = new \Raven_Client($key);
    }

    public function send($message, $level, $extra = [], $tags = [])
    {
        $extra['_trace'] = debug_backtrace();
        $this->client->captureMessage($message, [], [
            'level' => $level,
            'extra' => $extra,
            'tags' => $tags
        ]);
    }

    public static function info($key, $message, $extras=[], $tags=[])
    {
        $static = new static($key);
        $static->send($message, 'info', $extras, $tags);
    }
    public static function debug($key, $message, $extras=[], $tags=[])
    {
        $static = new static($key);
        $static->send($message, 'debug', $extras, $tags);
    }

    public static function warning($key, $message, $extras=[], $tags=[])
    {
        $static = new static($key);
        $static->send($message, 'warning', $extras, $tags);
    }

    public static function error($key, $message, $extras=[], $tags=[])
    {
        $static = new static($key);
        $static->send($message, 'error', $extras, $tags);
    }
}

最后

  • 以上为自行进行处理的方案,若各位有好的处理方案欢迎大家评论留言,让我们一同进步。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
thinkphp6中,异常处理是通过异常类来实现的。当系统出现异常时,会抛出一个异常对象,我们可以通过捕获这个异常对象来进行异常处理。以下是一个简单的异常处理示例: 1. 在控制器中抛出一个异常: ```php throw new \think\Exception('这是一个异常'); ``` 2. 在应用的异常处理类中进行异常处理: ```php namespace app\exception; use think\exception\Handle; use think\Response; use Throwable; class Http extends Handle { public function render($request, Throwable $e): Response { // 根据不同异常类型进行处理 if ($e instanceof \think\Exception) { // 返回错误信息 return json(['msg' => $e->getMessage()], 500); } // 其他异常交给系统处理 return parent::render($request, $e); } } ``` 注意,上面的代码中,我们继承了think\exception\Handle类,并重写了它的render方法。render方法接受两个参数:$request表示当前请求对象,$e表示抛出的异常对象。在这个方法中,我们可以根据不同的异常类型进行处理,并返回一个Response对象。如果我们不需要对异常进行特殊处理,可以直接调用父类的render方法,让系统进行默认的异常处理。 3. 在应用的配置文件中配置异常处理类: ```php return [ // 异常处理类 'exception_handle' => 'app\exception\Http', ]; ``` 在上面的配置中,我们将异常处理类设置为app\exception\Http。这样,在应用出现异常时,系统就会自动调用这个类的render方法进行异常处理。 除了上面的方法,thinkphp6还提供了其他的异常处理方式,比如使用自定义的异常类、使用异常监听器等。你可以根据自己的需求选择合适的方式进行异常处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

maSen.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值