0

There are a few functions in php that throw errors when they fail, such as ftp_login. If I have this code.

try {
    $result = ftp_login($conn_id, $ftp_user_name, 'incorrectPassword');
    if (!$result) {
        throw new Exception('Could not login.');
    }
} catch (Exception $e) {
    echo $e->getMessage() . ' - ' . error_get_last();
}

It will not catch because of the error. Is the appropriate thing in this case to use an Error Control Operator like so?

try {
    $result = @ftp_login($conn_id, $ftp_user_name, 'incorrectPassword');
    if (!$result) {
        throw new Exception('Could not login.');
    }
} catch (Exception $e) {
    echo $e->getMessage() . ' - ' . error_get_last();
}

This allows me to react to the error, however it suppresses errors and would be a major performance hit. How can I judge which is the right approach, and is there any other alternatives I'm not considering?

1

Register your own error handler with set_error_handler. Within that error handler, throw the exception.

If now ftp_open throws an error, the exception from your custom error handler behave just as if ftp_open threw it.

  • I know this is not a debugging site, but how could I apply set_error_handler to this function? I'm having trouble applying the information in the docs to this situation. php.net/manual/en/function.set-error-handler.php – Goose Sep 21 '16 at 16:54
  • 1
    A error handler is called when a php error occurs; it overrides the default behaviour (which is printing the error out) – marstato Sep 21 '16 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.