You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel API中通过beyondcode/laravel-query-detector抛出自定义异常

解决Laravel Query Detector触发自定义异常的方案

1. 创建自定义输出类

在app/QueryDetector目录下新建ThrowExceptionOutput.php(目录不存在则手动创建),实现包的Output接口:

<?php

namespace App\QueryDetector;

use BeyondCode\QueryDetector\Contracts\Output;
use BeyondCode\QueryDetector\Result;
use App\Exceptions\NPlusOneQueryException;

class ThrowExceptionOutput implements Output
{
    public function handle(Result $result): void
    {
        // 仅在APP_DEBUG=true时触发异常
        if (!config('app.debug')) {
            return;
        }

        $errorMsg = sprintf(
            "检测到N+1查询问题:关联 [%s] 在 [%s] 中被重复查询 %d 次",
            $result->getRelationName(),
            $result->getCaller(),
            $result->getCount()
        );

        // 抛出自定义异常,也可直接用系统Exception类
        throw new NPlusOneQueryException($errorMsg);
    }
}

如果需要专属异常类,可在app/Exceptions下新建NPlusOneQueryException.php:

<?php

namespace App\Exceptions;

use Exception;

class NPlusOneQueryException extends Exception
{
    // 可根据需求自定义异常逻辑
}

2. 修改Query Detector配置

打开config/query-detector.php,将自定义输出类加入output数组,可保留原有日志输出:

'output' => [
    \BeyondCode\QueryDetector\Outputs\Log::class,
    \App\QueryDetector\ThrowExceptionOutput::class,
],

3. 生效配置

执行Artisan命令清除配置缓存,确保修改生效:

php artisan config:clear

功能说明

  • 开发环境(APP_DEBUG=true)下,检测到N+1查询会直接抛出异常,中断请求,强制开发者处理该问题;
  • 生产环境(APP_DEBUG=false)仅记录日志,不影响业务正常运行;
  • 若不需要日志输出,可将Log::class从output数组中移除。

内容的提问来源于stack exchange,提问作者Petro Gromovo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:43:20