I'm working on a plugin that hooks into Craft's Guest Entries plugin.

I want to send a confirmation mail after an entry has been saved. This works nicely so far.

Now I want to catch any errors in the mail service. This works nicely so far. Here's my code:

private function mailHandler($from, $to, $subject, $text)
        $message = new \craft\mail\Message;


    catch (\Exception $e)
        echo \Craft::$app->view->renderTemplate('error', ['error' => 'Test']);

There are two problems I'm facing:

1) I have to "stop" the controller action, that's why I need the die. This seems dirty though, is there any other way I could stop the controller?

2) If I do it like this, my error template is rendered, but without any CSS. What am I missing there?

Thanks a ton for your help!

1 Answer 1


You can see common patterns for this in Craft's own controllers.

For example in https://github.com/craftcms/cms/blob/master/src/controllers/EntriesController.php#L499-L507, if there's a problem, you can catch the error, set it on a route variable and return null so the original template can display it.

Craft::$app->getSession()->setError(Craft::t('app', 'Couldn’t duplicate entry.'));

// Send the original entry back to the template, with any validation errors on the clone
    'entry' => $entry

return null;

If you don't want to let the original template handle the error, then you should be able to do something like this from your controller:

return $this->renderTemplate('error', ['error' => 'Test']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.