dongtui2029 2014-10-09 11:56 采纳率: 0%
浏览 29

如何向用户显示捕获的错误,避免这些常见的陷阱?

If your website catches an exception that you want reported back to the users as feedback, what is an elegant way to handle it without running into these problems:

  1. The error happened on the middle of the page, and if you directly print the error message when caught it will be sitting somewhere in the middle of a broken page.

  2. Using ob_start() can make sure you only print content after it has been processed and there are no errors, fixing the issue at 1), but it carries a performance hit that would best be avoided.

  3. Redirecting to a new URL or the same one after catching an error can work really well (like redirecting back to a login form if the user posted the wrong password, with an error messsage, or to a generic page for more serious, application crashing errors). This leaves you prone to a redirection chain of errors though (recursive), that will time out the requests eventually leaving the user or the developer with no clear error message at all. Always redirecting on errors, especially the application crashing errors, seems to be a bad idea because of this.

  4. I noticed using ob_clean() WITHOUT ob_start() works on my project, deleting the echoed content already on a page. But the php manual states it should not work without ob_start(), and it should not even clear the echoed HTML, merely what was on the buffer. What is going on here?

  5. Rather than ob_start, you could save all your print/echo statements in an $array = array(). The performance hit is lesser as far as I understand, but that can make the code ugly to deal with.

    Appreciate the help

  • 写回答

1条回答 默认 最新

  • dongyiyu882684 2014-10-09 12:11
    关注

    Something that I do is that I have an index that includes the pages needed, so for example, if you wanted to see the contact page, you'd request index.php?page=contact

    The code looks something like this

    $return_code = 1;
    $return_code = include($page.'.php');
    if ($return_code != 1) {
        echo '<div class="error">'.$return_code.'</div>';
    }
    

    Inside your contact page, you do whatever stuff you need to do, and if there is an error and you'd like to stop execution of the page and just display the error, simple do a return

    <?php
    // If an error happens, simply
    return "Error text";
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能