在PHP / codeIgniter捕获意外终止 [英] Capturing unexpected termination in PHP / CodeIgniter

查看:584
本文介绍了在PHP / codeIgniter捕获意外终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用codeIgniter举办一个RESTful API和我想捕捉不会返回预期状态code API的任何回应。这可能是用一个例子最容易解释。一般情况下,我的code是这样的:

I'm using CodeIgniter to host a RESTful API and I'd like to capture any API response that does not return an expected status code. This is probably most easily explained with an example. In general, my code looks like this:

function post_comment()
{
     $comment = $_POST['comment'];
     $result = do_something_with_comment($comment);

     if ($result === true)
     {
         return_json_response(200, 'OK!');
     }
     else
     {
         return_json_response(400, 'Something terrible happened...');
     }
}

返回无论是200还是400是完全有效的。我的问题是:如何捕捉错误,当do_something_with_comment()有一个致命的错误,或者如果我离开打印调试do_something_with_comment内()。在前一种情况下,我将永远不会达到return_json_response()。在后一种情况下,我会实现它,但是屏幕的调试会损坏JSON响应。

Returning either a 200 or 400 is perfectly valid. My problem is: how to capture errors when do_something_with_comment() has a fatal error, or if I leave a print debug inside of do_something_with_comment(). In the former case, I'll never reach return_json_response(). In the latter case, I'll reach it, but the screen debug will corrupt the JSON response.

有什么方法创建一个围绕这个通用包装器来捕捉任何意外输出或终止?

Is there any way to create a generic wrapper around this to capture any unexpected output or termination?

推荐答案

在一般你可以:

使用异常/异常处理尽可能多地

Use exception /exception handling as much as possible

寄存器,变换PHP错误到例外的自定义的ErrorHandler,比如把这个在你的config / config.php文件的顶部

Register a custom errorhandler that transforms PHP errors into exceptions, for instance put this in top of your config/config.php

function my_error_handler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno))
    {
        // This error code is not included in error_reporting
        return;
    }
    log_message('error', "$errstr @$errfile::$errline($errno)" );
    throw new ErrorException( $errstr, $errno, 0, $errfile, $errline );
}
set_error_handler("my_error_handler");

注册未捕获的异常处理程序,把这样的事情在你的config / config.php文件

Register an uncaught exception handler, put something like this in your config/config.php

function my_exception_handler($exception)
{
    echo '<pre>';
    print_r($exception);
    echo '</pre>';
    header( "HTTP/1.0 500 Internal Server Error" );
}
set_exception_handler("my_exception_handler");

修改

设置终止处理程序:

function my_fatal_handler()
{
    $errfile = "unknown file";
    $errstr  = "Fatal error";
    $errno   = E_CORE_ERROR;
    $errline = 0;
    $error = error_get_last();
    if ( $error !== NULL )
    {
        echo '<pre>';
        print_r($error);
        echo '</pre>';
        header( "HTTP/1.0 500 Internal Server Error" );
    }
}
register_shutdown_function("my_fatal_handler");

设置转换成断言异常的自定义断言处理程序,把这样的事情在你的config / config.php文件:

Set a custom assert handler that converts asserts into exceptions, put something like this in your config/config.php:

function my_assert_handler($file, $line, $code)
{
    log_message('debug', "assertion failed @$file::$line($code)" );
    throw new Exception( "assertion failed @$file::$line($code)" );
}
assert_options(ASSERT_ACTIVE,     1);
assert_options(ASSERT_WARNING,    0);
assert_options(ASSERT_BAIL,       0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

然后,这就是你的答案后,使用包装像这样在控制器

Then, and this is your answer, use wrappers like this in your controllers

public function controller_method( )
{
    try
    {
        // normal flow
    }
    catch( Exception $e )
    {
        log_message( 'error', $e->getMessage( ) . ' in ' . $e->getFile() . ':' . $e->getLine() );
        // on error
    }
}

您可以调整和自定义整个事情你喜好!

You can tune and customize the whole thing to your likings!

希望这有助于。

修改

您还需要拦截CI show_error方法。把这个应用程序/核心/ MY_exceptions.php:

You will also need to intercept the CI show_error method. Place this in application/core/MY_exceptions.php:

class MY_Exceptions extends CI_Exceptions
{
    function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        log_message( 'debug', print_r( $message, TRUE ) );
        throw new Exception(is_array($message) ? $message[1] : $message, $status_code );
    }
}

和应用留下/配置/ database.php中这对FALSE设置有转换成异常的数据库错误。

And leave in application/config/database.php this setting on FALSE to have database errors converted into exceptions.

$db['default']['db_debug'] = TRUE;

CI有几个(很)的弱点,如异常处理,但这会很长的路要走纠正。

CI has a few (very) weak points, such as exception-handling but this will go a long way correcting that.

这篇关于在PHP / codeIgniter捕获意外终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆