Created
April 15, 2019 10:21
-
-
Save Caffe1neAdd1ct/09f1c094fa547d90db3ef533ec707bd5 to your computer and use it in GitHub Desktop.
Capturing Laravel Database connection exceptions with Sentry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Custom\Support; | |
use \Illuminate\Support\ServiceProvider; | |
class SessionRejectServiceProvider extends ServiceProvider { | |
public function register() | |
{ | |
$me = $this; | |
$this->app->bind('session.reject', function ($app) use($me) { | |
return function ($request) use ($me, $app) { | |
return call_user_func_array(array($me, 'reject'), array($app, $request)); | |
}; | |
}); | |
} | |
/** | |
* Returning a true value forces session handler to use the array driver | |
* Capture failing database session connections and report to sentry | |
* @param Illuminate\Foundation\Application $app | |
* @param Illuminate\Http\Request $request | |
* @return boolean | |
*/ | |
protected function reject($app, $request) | |
{ | |
/** revert to array driver for console commands and tasks */ | |
if ($this->app->runningInConsole()) { | |
return true; | |
} | |
/** Manually boot sentry client and hooks */ | |
$this->app->forceRegister(\Sentry\SentryLaravel\SentryLaravelServiceProvider::class); | |
$sentryProvider = $this->app->getRegistered(\Sentry\SentryLaravel\SentryLaravelServiceProvider::class); | |
$sentryProvider->boot(); | |
/** @var \Raven_Client $sentry */ | |
$sentry = \app('sentry-laravel'); | |
/** return false to trigger loading of db session adapter again after sentry has been loaded to capture the issue */ | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This service provider registers a call back when a session adapter fails to collect a session connection. Sessions are initialised before Sentry and other service providers meaning a database connection failure would trigger the whoops handler but not the Sentry error handlers as it hasn't been registered with the App yet.
This session rejection hook starts the sentry provider, registers the error handlers and asks the session handler to re-try a collection of the session adapter. At this point if the session adapter fails again the registered Sentry error handlers will be triggered.
This is very helpful for triggering Slack and other alerts for when the database is unavailable and to register the Sentry handlers a bit earlier in the app lifecycle to capture more errors.