Display different message in case of timeout

Asked

Viewed 671 times

0

I have an app web in PHP where I submit a set of invoices. This processing is done according to the due date. As some days take longer to finish than others, it may occur timeout.

For being a legacy system, I can’t increase the maximum running time any longer (set_time_limit).

When this occurs, I display the generic message of "Processing error", which does not make it clear to the user that the problem was very long execution time.

How can I control to display a message different in case of timeout?
Ideally in Javascript, would be possible?

  • The ideal solution would be for you to have a separate process or server that will consume these Jobs which are too slow to be processed in a single request, and after they are processed warn the user about the result. As it is a legacy system, I don’t know if such a change would be possible in your case. That answer on Soen have some examples if any help.

  • I guess it depends on how it’s done. Roughly speaking, PHP only serves to render the page, that is, if the processing delays the "delivery" of the page (it is processing for a long time), I think a solution via JS would be better, asynchronously, and the user does not think that the page or the site has crashed.

  • Have you ever tried to capture this error with Try catch ? No JS even ? If you can capture this error, you can display a custom message to your user, since it seems to me that your problem is the user knowing what happened..

  • @Matheusbarbosa tried yes but without success.. none of the Try catch controls caught my return.. (neither taking real time nor simulating with a comeback event)

2 answers

1


Call via AJAX the PHP file that does this processing, and then scan the response’s HTTP status code to see if it occurred timeout:

$.ajax({
    type: 'GET',
    url: 'processamento.php',
    cache: false,
    dataType: 'json',
    success: function(response) {
        // código normal
    },
    error: function(error) {
        if (error.status == '408' || error.status == '504') {
            alert('Tempo esgotado! Processamento tomou mais tempo do que o permitido');
        }
    }
});

Just illustrating, the code 408 indicates that the server is processing the request for a long time, while the 504 indicates that there may be error or non-existence of the server.

  • 1

    Massa, @Edson. I only added a few links for those who want to see what the codes are but this control in solves the problem!!

0

The ideal would be for you to place these invoices in a queue and process them asynchronously.

But as it is a legacy system and maybe you can not make this change, to capture the timeout error you can work with the function register_shutdown_function.

Following example:

<?php
ini_set("display_errors", "0"); // ocultando mensagens de erro
set_time_limit(3); // setando tempo máximo de execução para 3 segundos

class Fatura {    
    public function __construct() {
        // registrando função que vai ser chamada quando o script for finalizado (com sucesso ou não)
        register_shutdown_function(array($this, 'shutdown'));
    }

    private function shutdown() {
        $error = error_get_last();
        if ($error !== null) { // verificando se ocorreu algum erro durante a execução
            $message = $error["message"];
            if (strpos($message, "Maximum execution time") !== false) {
                die(json_encode(array("success" => false, "msg" => "Tempo máximo de execução foi excedido.")));
            }

            die(json_encode(array("success" => false, "msg" => "Desculpe, não foi possível finalizar o processamento.")));
        }
    }

    public function gerar() {
        for ($i = 0; $i < 1000000; $i++) {
            echo "Gerando fatura $i<br/>";
            sleep(1);
        } 
        die(json_encode(array("success" => true)));
    }
}

$fatura = new Fatura();
$fatura->gerar();
  • Vlw for the answer, diego. I tried to use but I realized that I don’t have as much access to the site’s php.. I need to try something via via JS =/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.