7

Let's say I have the following piece of code.

To test this, I change the server IP to mimic the error messages. The IP below doesn't exist so the Unhandled Exception message is: Cannot connect to 10.199.1.7. Error 113. No route to host

This displays an ugly screen with PHP code. Is it possible to catch this error?

try {
      $ssh = new Net_SSH2('10.199.1.7');        
  if (!$ssh->login('deploy', $key)) {
       throw new Exception("Failed login");
  }
} catch (Exception $e) {
     ???
}
hakre
  • 178,314
  • 47
  • 389
  • 754
sdot257
  • 9,100
  • 24
  • 78
  • 115

2 Answers2

13

Looked through library.

user_error('Connection closed by server', E_USER_NOTICE);

It triggers errors. You can handle those errors using http://php.net/manual/en/function.set-error-handler.php

e.g.

// Your file.php
$ssh = new Net_SSH2('10.199.1.7');        
$ssh->login('deploy', $key);

// bootstrap.php
// This will catch all user notice errors!!!
set_error_handler ('errorHandler', E_USER_NOTICE)

function errorHandler($errno, $errstr, $errfile, $errline) {
    echo 'Error';
    // Whatever you want to do.
}
E_p
  • 3,088
  • 14
  • 28
  • Having a hard time figuring this out. How would i go about implementing this into my existing code above? – sdot257 Nov 27 '12 at 17:36
  • So basically include the `boostrap.php` file inside `file.php` and it should work? – sdot257 Nov 27 '12 at 17:40
  • Good call on the user_errors. I went Google-ing when I saw this question and landed on someone's forked implementation on Github, using exceptions, rather than the official one on SourceForge. My answer is 100% wrong so I marked it for deletion. Thanks for the catch and +1 – EmmanuelG Nov 27 '12 at 18:07
  • Np, I found git hub version first too. – E_p Nov 27 '12 at 18:08
  • Just what I was looking for. Thanks. – Matt Setter Apr 01 '14 at 08:10
0

You can use @ in front of you function call. @ operator