37

I have the following method which sends out an e-mail:

Mail::send('emails.configuration_test', array(), function($email)use($request){
    $email->to($request->test_address)->subject('Configuration Test');
});

If the above errors out, I'd like to be able to catch the exception. When I use the following:

try{
    Mail::send('emails.configuration_test', array(), function($email)use($request){
        $email->to($request->test_address)->subject('Configuration Test');
    });
}
catch(Exception $e){
    // Never reached
}

the exception is never caught. Instead I get a Laravel stacktrace as the response if the send() method errors out.

How do I catch the exception in this case?

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
  • 2
    If the file is namespaced, you'll need to `catch(\Exception $e)` (or put `use Exception` at the top of the file). Right now, it's probably catching something like `App\Http\Controllers\Exception`. http://php.net/manual/en/language.namespaces.php – ceejayoz Jan 06 '17 at 20:37
  • Or import it at the top. Which I assume he has. – DevK Jan 06 '17 at 20:37
  • 3
    @devk If he's getting a stacktrace after `catch(Exception $e)` he hasn't. – ceejayoz Jan 06 '17 at 20:38
  • @ceejayoz Fair enough. I thought you get the Laravel exception message. – DevK Jan 06 '17 at 20:40
  • 3
    @devk All Laravel exceptions are eventually subclasses (or sub-sub-sub-subclasses) of the root `\Exception`, so catching `\Exception` should cover literally everything if done correctly. – ceejayoz Jan 06 '17 at 20:43

1 Answers1

73

Using the root namespace \Exception did the trick.

Instead of:

catch(Exception $e){
    // Never reached
}

I used:

catch(\Exception $e){
    // Get error here
}
Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
  • 2
    Is this really a good way to use exceptions? Couldn't we create a more specific exception for a mail send error and catch that? I was searching the framework for such an exception to catch, but couldn't find one :( I suppose the main goal here is to let the code continue if a mail fails to send rather than stop executing and abort. But the catch of the universal exception doesn't express that intention very clearly. Just my take on it. – mwal Dec 22 '18 at 20:56
  • Have realised the key point here is that laravel uses Symfony swift mailer, so simply need to look at the docs for that, not laravel. – mwal Dec 22 '18 at 21:12
  • Generally to find a specific exception get_class() can be used, like this: `catch (\Exception $e){ dd(get_class($e)); }` . Then use the output like this: `catch (\Swift_TransportException $e){...` – Macke Feb 09 '23 at 01:25