How to render template instead of throwing an error? 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)
{
    try
    {
        $message = new \craft\mail\Message;

        $message-&gt;setFrom($from);
        $message-&gt;setTo($to);
        $message-&gt;setSubject($subject);
        $message-&gt;setTextBody($text);

        Craft::$app-&gt;mailer-&gt;send($message);
    }
    catch (\Exception $e)
    {
        echo \Craft::$app-&gt;view-&gt;renderTemplate('error', ['error' =&gt; 'Test']);
        die();
    }
}


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!
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-&gt;getSession()-&gt;setError(Craft::t('app', 'Couldn’t duplicate entry.'));

// Send the original entry back to the template, with any validation errors on the clone
$entry-&gt;addErrors($clone-&gt;getErrors());
Craft::$app-&gt;getUrlManager()-&gt;setRouteParams([
    'entry' =&gt; $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-&gt;renderTemplate('error', ['error' =&gt; 'Test']);