11

What's the best way to prevent exceptions in my plugin from blowing up my entire page? try/catch and return null, and then check for null in the template?

For example: my plugin fetches data from a remote REST API. If that request fails for any reason I get an error page. I understand why, but I'm looking for the best way to handle it. I'd appreciate any input, even if it seems glaringly obvious to you.

10

Yep, Craft makes pretty liberal use of try/catch blocks. Wrap your HTTP request in that, and return whatever makes sense in the context – null, false, or maybe an empty array.

Probably also worth logging the error, so the developer can investigate why it’s not working, using Craft::log().

Remember when catching exceptions, that there’s a good chance the exception class won’t be in Craft’s namespace. So you’ll probably need to prepend the exception class(es) with \.

So to put it all together:

try
{
    // Make the HTTP request
    // ...
}
catch (\Exception $e)
{
    Craft::log('The request to domain.com failed: '.$e->getMessage(),
               LogLevel::Warning, false, 'mypluginhandle');

    return false;
}
8

This is what I generally do if I want to catch exceptions but still output an error to the browser. This example uses Craft's included Guzzle class to make the http request.

try 
{
    // create client
    $client = new \Guzzle\Http\Client('https://twitter.com');

    // get response
    $response = $client->get()->send();
}
catch (\Guzzle\Http\Exception\CurlException $e) 
{
    // throw a craft exception which displays the error cleanly
    throw new HttpException(400, 'Internet connection not available');
}

You can of course do anything you want inside the catch block, such as rendering a template and providing it with information about the error:

$html = craft()->templates->render('error', array(
    'message' => 'Internet connection not available'
));
  • If the call was invoked from a template and I call craft()->templates->render, what's the result? Does the template rendered by this call replace the whole page? – ray hatfield Jun 18 '14 at 6:54
  • I've updated my answer to reflect that it simply returns html code but you can then do whatever you want with this. – Ben Croker Jun 18 '14 at 7:00
  • @BenCroker Thanks for mentioning Guzzle in your answer. I've been completely missing out until now! – Matt Stein Jun 24 '14 at 20:28
  • 1
    Guzzle is amazing!! – Ben Croker Jun 25 '14 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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