Split TRY and CATCH EXCEPTION across different .php include files

那年仲夏 提交于 2019-12-11 09:39:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!