Kamil
Kamil

Reputation: 13931

Try catch not working in PHP?

I'm working on web-service.

I'm trying to catch error. My problematic code is:

    try
    {
    $query = "UPDATE Users
              SET 
                Latitude=?,
                Longitude=?,
                Address=?,
                LocationTimestamp=?
              WHERE Id=?";

        $stmt = $this->link->prepare($query);
        $stmt->bind_param('ddssi', $Latitude, $Longitude, $Address, $LocationTimestamp, $Id);
        $stmt->execute();


        $affected_rows = $stmt->affected_rows;

    }

    catch(Exception $exc)
    {
        file_put_contents("log/error.txt",$exc->getMessage());
    }

I expected, that catch block will catch all errors and PHP will not produce any errors on output. However - on output I see something like this:

Warning: Creating default object from empty value in /srv/webservice/server.php on line 119

I want to avoid any HTML on output, because this is web-service and I have JSON interpreter on client side.

My question is:

How to debug service like this, when I have no access to PHP output? I would like to redirect all errors, warnings etc. to file.

Upvotes: 0

Views: 928

Answers (2)

Mark Baker
Mark Baker

Reputation: 212412

A Warning is not an Exception..... you can catch Exceptions, but not Warnings/Notices/Errors/etc. If you want to make warnings catchable you need to convert them to Exceptions with a user defined error handler using set_error_handler()

class MyCustomException extends Exception {
    public static function errorHandlerCallback($code, $string, $file, $line, $context) {
        $e = new self($string, $code);
        $e->line = $line;
        $e->file = $file;
        throw $e;
    }
}

set_error_handler(['MyCustomException', 'errorHandlerCallback'], E_ALL);

Upvotes: 3

Richard
Richard

Reputation: 2815

You get an PHP warning, not an Exception. Maybe this helps to save your errors direct:

ini_set("log_errors", true);
ini_set("error_log", "log/error.txt");

This logs all PHP errors and warnings (and notices) into this file.

After the code block, you can disable it, if you want so:

ini_set("log_errors", false);

Upvotes: 1

Related Questions