问题
Is there any way in PHP to split try
and catch
across two different "include files", putting the try
in one file and the catch
in another?
Something like:
<?php
include('begin_try.php');
...
//some code goes here
...
include('end_try_and_catch_exceptions.php');
?>
//filename: begin_try.php:
<?php
header('Content-type: application/json');
try {
?>
//filename: end_try_and_catch_exceptions.php:
<?php
} catch (Exception $e) {
echo json_encode(array(
'error' => array(
'code' => $e->getCode(),
'message' => $e->getMessage()
)
));
}
?>
回答1:
It's not syntactically possible to use try-catch like that, but you can use the set_exception_handler function to register a function that will catch all exceptions that are not otherwise caught:
set_exception_handler(function ($e) {
echo json_encode(array(
'error' => array(
'code' => $e->getCode(),
'message' => $e->getMessage()
)
));
});
来源:https://stackoverflow.com/questions/26694835/split-try-and-catch-exception-across-different-php-include-files