Skip to main content

Safely catch a "Allowed memory size exhausted" error in PHP


I have a gateway script that returns JSON back to the client. In the script I use set_error_handler to catch errors and still have a formatted return.



It is subject to 'Allowed memory size exhausted' errors, but rather than increase the memory limit with something like ini_set('memory_limit', '19T') , I just want to return that the user should try something else because it used to much memory.



Are there any good ways to catch fatal errors?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. As this answer suggests, you can use register_shutdown_function() to register a callback that'll check error_get_last().

    You'll still have to manage the output generated from the offending code, whether by the @ (shut up) operator, or ini_set('display_errors', false)



    ini_set('display_errors', false);

    error_reporting(-1);

    set_error_handler(function($code, $string, $file, $line){
    throw new ErrorException($string, null, $code, $file, $line);
    });

    register_shutdown_function(function(){
    $error = error_get_last();
    if(null !== $error)
    {
    echo 'Caught at shutdown';
    }
    });

    try
    {
    while(true)
    {
    $data .= str_repeat('#', PHP_INT_MAX);
    }
    }
    catch(\Exception $exception)
    {
    echo 'Caught in try/catch';
    }


    When run, this outputs Caught at shutdown. Unfortunately, the ErrorException exception object isn't thrown because the fatal error triggers script termination, subsequently caught only in the shutdown function.

    You can check the $error array in the shutdown function for details on the cause, and respond accordingly. One suggestion could be reissuing the request back against your web application (at a different address, or with different parameters of course) and return the captured response.

    I recommend keeping error_reporting() high (a value of -1) though, and using (as others have suggested) error handling for everything else with set_error_handler() and ErrorException.

    ReplyDelete
  2. you could get the size of the memory already consumed by the process by using this function memory_get_peak_usage documentations are at http://www.php.net/manual/en/function.memory-get-peak-usage.php I think it would be easier if you could add a condition to redirect or stop the process before the memory limit is almost reached by the process. :)

    ReplyDelete
  3. UPDATE

    This answer is insufficient for fatal errors -- the memory exhaustion problem in this case. The answer from @Bracketworks is a more correct way to do this sort of thing if you want to handle the error at the time it happens.

    I'm not deleting my answer here to hopefully help others avoid this mistake!



    I wasn't clear on whether or not you were already doing this, so here's how I would handle this problem:

    <?php

    // Create custom error handler that turns ALL php errors into Exceptions.
    // Then when an exception is caught you can decide how to handle it.
    function err_handler($severity, $message, $filepath, $line)
    {
    $msg = "$message in $filepath on line $line";
    throw new PhpErrException($msg);
    }

    // set your custom error handler
    set_error_handler('err_handler');

    // --- output json content type headers here ---

    try {

    // do stuff
    $json = '{ "errmsg": "", "value": "42" }';

    } catch (Exception) {
    if (strstr($e->getMessage(), 'Allowed memory size exhausted')) {
    $json = '{ "errmsg": "You are a MEMORY HOG!" }';
    } else {
    $json = '{ "errmsg": "Your request failed for an unkown reason" }';
    }
    }

    echo $json;

    ?>


    As for things like parse errors that you can't catch at runtime ... hopefully you've already eliminated those.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex