The True Exception Handlers in PHP and Javascript


@Jordan Hall tweets true exception handlers in PHP an Javascript.

Javascript Exception Handler

1
2
3
4
5
6
try {
  // something
} catch (e) {
   window.location.href = "http://stackoverflow.com/search?q=[js] + "
                        + e.message;
}
try {
  // something
} catch (e) {
   window.location.href = "http://stackoverflow.com/search?q=[js] + "
                        + e.message;
}

So if things go wrong, the page will be redirected to stackoverflow for answers.

PHP Exception handler

Similarly, here is the PHP versions:

1
2
3
4
5
try {
  // something
} catch (Exception $e) {
  header("Location: https://stackoverflow.com/search?q=[php] ".$e->getMessage());
}
try {
  // something
} catch (Exception $e) {
  header("Location: https://stackoverflow.com/search?q=[php] ".$e->getMessage());
}

You can split the try-catch into two files and let server automatically wrap your PHP code inside this big try-catch.

You will need phps auto_prepend_file and auto_append_file directives. and modify the .htaccess file.

1
2
php_value auto_prepend_file "/path/to/file/before.php"
php_value auto_append_file "/path/to/file/after.php"
php_value auto_prepend_file "/path/to/file/before.php"
php_value auto_append_file "/path/to/file/after.php"

Put the following in before.php

1
try {
try {

and put the rest in after.php

1
2
3
} catch (Exception $e) {
  header("Location: https://stackoverflow.com/search?q=[php] ".$e->getMessage());
}
} catch (Exception $e) {
  header("Location: https://stackoverflow.com/search?q=[php] ".$e->getMessage());
}

Alternatively, you can put these definitions in php.ini (requires cgi-mode, affects the whole webserver).

1
2
auto_prepend_file  = "/path/to/file/before.php"
auto_append_file   = "/path/to/file/after.php"
auto_prepend_file  = "/path/to/file/before.php"
auto_append_file   = "/path/to/file/after.php"

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
305 words
Last Post: git: How to Revert Some Files to a Revision?
Next Post: How to Ban Bad Bots by User Agent in .htaccess?

The Permanent URL is: The True Exception Handlers in PHP and Javascript

Leave a Reply