Skip to content

Instantly share code, notes, and snippets.

@JacobBennett
Last active September 30, 2023 09:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacobBennett/45b0bd18aebfe7d379a02456ef3a6f13 to your computer and use it in GitHub Desktop.
Save JacobBennett/45b0bd18aebfe7d379a02456ef3a6f13 to your computer and use it in GitHub Desktop.
Loading Laravel Sentry only for production

Loading Laravel Sentry package only for production

In the case that you don't want development errors making their way to Sentry for error tracking, you can use the code below to ensure that Sentry will only record exceptions when in production.

First, instead of loading the SentryLaravelServiceProvider in the config/app.php providers array, we will load it in our App/Providers/AppServiceProvider.php. This allows us to check the environment before loading the appropriate service providers.

Seconly, in our App/Exceptions/Handler.php we again check for the production environment before trying to capture the exception using Sentry. This second step prevents Sentry from trying to catch an exception when it isn't bound in the container.

<?php
// App/Providers/AppServiceProvider.php
...
public function register()
{
if ($this->app->environment('local')) {
// Dev only service providers
} else if ($this->app->environment('production')) {
$this->app->register(SentryLaravelServiceProvider::class);
}
}
// App/Exceptions/Handler.php
...
public function report(Exception $e)
{
if (app()->environment('production') && $this->shouldReport($e)) {
app('sentry')->captureException($e);
}
parent::report($e);
}
@techenby
Copy link

So you don't bother registering the Sentry facade?

@JacobBennett
Copy link
Author

@andreamswick No I don't. Don't use it anywhere but in my Handler class

@sensasi-delight
Copy link

Sentry documentation has provided the case on this link:
https://docs.sentry.io/platforms/php/guides/laravel/#local-development-and-testing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment