如何在Laravel应用程序发生错误时触发Webhook并推送错误详情?
Laravel错误Webhook通知配置实现步骤
1. 创建自定义Webhook通知类
首先用Artisan命令生成通知类:
php artisan make:notification ErrorWebhookNotification
打开生成的app/Notifications/ErrorWebhookNotification.php,修改内容如下:
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Http\Client\PendingRequest; class ErrorWebhookNotification extends Notification implements ShouldQueue { use Queueable; protected $exception; /** * 初始化通知实例 * * @param \Throwable $exception * @return void */ public function __construct(\Throwable $exception) { $this->exception = $exception; } /** * 指定通知投递渠道 * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['webhook']; } /** * 构造Webhook推送的错误数据 * * @param mixed $notifiable * @return array */ public function toWebhook($notifiable) { return [ 'error_message' => $this->exception->getMessage(), 'file_path' => $this->exception->getFile(), 'line_number' => $this->exception->getLine(), 'trace' => $this->exception->getTraceAsString(), 'timestamp' => now()->toIso8601String(), 'environment' => config('app.env'), 'request_url' => request()->fullUrl() ]; } /** * 配置Webhook请求头 * * @param \Illuminate\Http\Client\PendingRequest $request * @return void */ public function withWebhook(PendingRequest $request) { $request->withHeaders([ 'Content-Type' => 'application/json', // 若Webhook需要认证,取消下方注释并配置token // 'Authorization' => 'Bearer ' . config('services.error_webhook.token') ]); } }
2. 修改异常处理器触发通知
打开app/Exceptions/Handler.php,在register方法中添加异常报告逻辑:
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; use App\Notifications\ErrorWebhookNotification; use Illuminate\Support\Facades\Notification; class Handler extends ExceptionHandler { // 保留原有代码... /** * 注册异常处理回调 * * @return void */ public function register() { $this->reportable(function (Throwable $e) { // 排除无需通知的异常类型,比如404页面不存在、CSRF错误 $ignoreExceptions = [ \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class, \Illuminate\Session\TokenMismatchException::class ]; if (in_array(get_class($e), $ignoreExceptions)) { return; } // 发送Webhook通知 Notification::route('webhook', config('services.error_webhook.url')) ->notify(new ErrorWebhookNotification($e)); }); } }
3. 配置Webhook参数
在.env文件中添加Webhook地址(按需添加认证token):
ERROR_WEBHOOK_URL=https://your-target-webhook-endpoint.com # ERROR_WEBHOOK_TOKEN=your-webhook-auth-token
然后在config/services.php中添加对应配置项:
return [ // 保留原有配置... 'error_webhook' => [ 'url' => env('ERROR_WEBHOOK_URL'), 'token' => env('ERROR_WEBHOOK_TOKEN'), // 可选,根据Webhook要求配置 ], ];
4. 测试验证
在任意控制器方法中手动抛出异常测试:
throw new \Exception('测试Webhook错误通知');
触发该方法后,检查目标Webhook地址是否收到包含错误详情的POST请求。
可选优化点
- 异步处理:示例中已让通知类实现
ShouldQueue接口,确保通知异步发送,避免阻塞请求响应。 - 自定义数据:可在
toWebhook方法中添加更多上下文信息,比如当前登录用户ID、请求方法、请求参数等。 - 日志记录:可在发送通知前后添加日志,便于排查推送失败问题。
内容的提问来源于stack exchange,提问作者GanesH RahuL
相关产品推荐
相关产品推荐

