Search code examples
phpexceptionerror-handlingsentry

`sentry/sdk 2.x` - how to register it's error / exception handling


While we are using multiple instances of sentry at once I dropped the default initialization of the Sentry client and managed to create the Sentry client manually.

$client = ClientBuilder::create(
    [
        'dsn'         => $this->config->getDsn(),
        'environment' => $this->config->getEnvironment(),
        'release'     => $this->config->getRelease(),
        'error_types' => $this->config->getErrorReporting()
    ]
)->getClient();

I'm now able to capture exceptions / errors or messages manually.

$client->captureException( ... );

But what I don't get is how to register Sentry's exception / error handlers manually?


Solution

  • We handle global unhandled exceptions via integrations. Integrations work a bit different since they are essentially singletons and need to be able to keep a global state since we for example do not want to hook multiple times in the the global handlers.

    In order to achieve what you want, you need to use Hub instead of the Client directly.

    $client1 = Sentry\ClientBuilder::create([
      'dsn' => 'DSN'
    ])->getClient();
    
    $hub1 = new Sentry\State\Hub($client1);
    // Making a Hub current, tells the global integrations to send stuff to the client registered in this Hub
    Sentry\SentrySdk::setCurrentHub($hub1);
    
    // This will be caught by and send by $client1
    throw new Exception('DEMO TEST3');
    
    $client2 = Sentry\ClientBuilder::create([
      'dsn' => 'DSN'
    ])->getClient();
    
    $hub2 = new Sentry\State\Hub($client2);
    // Setting a new current hub here
    Sentry\SentrySdk::setCurrentHub($hub2);
    
    // This will be caught by and send by $client2
    throw new Exception('DEMO TEST4');
    

    So only one hub can be the current hub at a time, so one of your clients must be the one handling global exceptions. I hope this makes sense.