Search code examples
phpexceptioncachingpear

How does one access the Pear Cache_Lite error object?


I'm playing around with Pear's Cache_Lite and it looks really easy to use. One aspect which I can't quite get a handle on is how I can throw Exceptions to find out what the error was. As per the docs, in my $options array below, I've tried 'pearErrorMode' => CACHE_LITE_ERROR_DIE, which will stop the script and show me the error (namely, that the cacheDir doesn't exist, as in the code below).

However, I don't necessarily want to show this error to the user (i.e. I'll probably log it, and give them a custom message). I then thought that I could use 'pearErrorMode' => CACHE_LITE_ERROR_RETURN which is supposed to return the Pear error object. My impression (obviously incorrect) was that echo $e->getMessage(); would then access the Pear error object and print it out. However, all I got was a blank screen. My question then, is how I can do a standard try/catch, and then access the error object? My code snippet (more or less a copy from the Pear Manual) is presented below:

<?php
    require_once('Cache/Lite.php');
    $id = '123';
    $options = array(
        'cacheDir' => '/oops_I_am_not_a_directory/', //this is the problem line!
        'lifeTime' => 3600
    );
    try {
       $Cache_Lite = new Cache_Lite($options);
       if ($data = $Cache_Lite->get($id)) {
       echo $data;
    } else { 
       $data = "blah";
       $Cache_Lite->save($data);
    }   
    } catch (Exception $e) {
       echo $e->getMessage();   
    }
    ?>

Solution

  • _RETURN returns the error object as return value from the functions:

    $error = $cache->get(..);
    $error = $cache->save(..);
    

    You can check if it's an error by using

    $retval = $cache->get(..);
    if (PEAR::isError($retval)) {
        echo $retval->getMessage() . "\n";
    }
    

    Alternatively, you can make it throw exceptions by setting CACHE_LITE_ERROR_EXCEPTION or PEAR_ERROR_EXCEPTION