0

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.

Kamil
  • 13,363
  • 24
  • 88
  • 183

2 Answers2

3

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);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Maybe also worth to say is, that you could turn on output buffering and then use `error_get_last()` to get the last error if one occurred. And to convert warnings into exceptions this might be related: http://stackoverflow.com/q/1241728/3933332 – Rizier123 May 07 '15 at 16:54
1

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);
Richard
  • 2,840
  • 3
  • 25
  • 37