Laravel 5 - How Do You Catch an Mail::send() Error?
Asked Answered
C

1

40

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?

Crone answered 6/1, 2017 at 20:33 Comment(5)
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. php.net/manual/en/language.namespaces.phpAweigh
Or import it at the top. Which I assume he has.Scorcher
@devk If he's getting a stacktrace after catch(Exception $e) he hasn't.Aweigh
@Aweigh Fair enough. I thought you get the Laravel exception message.Scorcher
@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.Aweigh
C
74

Using the root namespace \Exception did the trick.

Instead of:

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

I used:

catch(\Exception $e){
    // Get error here
}
Crone answered 9/1, 2017 at 3:22 Comment(3)
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.Seafowl
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.Seafowl
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){...Restoration

© 2022 - 2024 — McMap. All rights reserved.