在PHP页面上处理错误的最佳方法? [英] Best way to handle errors on a php page?

查看:139
本文介绍了在PHP页面上处理错误的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我的网页看起来像这样:

  if($ _ GET ['something'] =='somevalue' )
{
$ output。='somecode';

//创建数据库查询,获取一行
// ...
$ row = $ stmt-> Fetch(PDO :: ASSOC);

if($ row!= null)
{
$ output。='morecode';

if(somethingIsOK())
{
$ output。='更多的页面输出';
}
else
{
$ error ='某事绝对不行。
}
}
else
{
$ error ='该行不存在。
}
}
else
{
$ error ='某物不是有效值';
}

if($ error =='')//无错误
{
//页

else //一个错误
{
//显示页面上发生的任何错误
}

我在做事情的方式有效,但是对于很明显的事情来说,这是非常麻烦和乏味的:假设我在代码的中间调用一个函数,或者想要检查一个变量,或验证一个DB查询返回一个有效的结果,如果失败,我想输出一个错误?我必须再创建一个if / else块并将所有代码移动到新的if块中。这似乎不是一个聪明的做事方式。



我一直在阅读关于try / catch,并一直在考虑把我的所有代码放在一个try语句,然后让代码顺序运行,没有任何if / else块,如果某些失败只是抛出一个异常。从我读过的,这将停止执行,并使其直接跳到catch块(就像一个失败的if语句将转到else块),然后我可以输出错误消息。但是,这是可以接受还是标准的做法?



在构建和输出HTML页面的php应用程序中处理错误,致命或不可靠的最佳方式是什么?我不想只用一个空白的屏幕,因为这将非常用户非常友好,而是想在页面的主体中输出一个消息,仍然允许页眉和页脚显示。



感谢您的意见!

解决方案

有很多方法可以处理这个,坦白说,他们都不是内在的正确 p>

您将不得不为自己决定,哪种方法对您来说更为舒适 - 它始终是偏好的主体(尽管有某些技术您应该避免,并有很好的理由)



它将高度依赖于您如何拆分逻辑,但是我倾向于将所有可在函数中返回非致命错误的代码包含在内,并使用返回值所述函数的值表示有错误。



对于致命错误我倾向于使用例外(使用 try-catch 块)。



现在只需要清楚:




  • 非致命错误是一个错误,您可以从中恢复即使发生了错误,仍然有一些代码可以执行并产生一些有价值的输出。例如,如果您想使用 NTP 协议获取当前时间,但服务器未响应,则可以决定使用本地时间函数,仍然向用户显示一些有价值的数据。

  • 一个致命的错误是您无法从恢复<这意味着发生了一些非常糟糕的事情,唯一可以做的就是告诉你的用户页面无法做到这一点。例如,如果您从数据库中获取一些数据,并获得 SQL Exception - 没有任何有价值的数据可以显示,您只能通知用户。 >





非致命错误(使用函数返回)



使用函数返回作为处理非致命问题的一个方法的一个很好的例子是在页面上尝试显示某些文件的内容的功能,当这不是主要目的页面(例如,您将有一个显示徽章的功能,从文本文件中获取,在每个页面上 - 我知道这是非常牵强,但与我承担)。

  function getBadge($ file){
$ f = fopen($ file,'r');
if(!$ f){
return null;
}
..做一些处理..
返回$徽章;
}

$ badges = getBadges('badges.txt');
如果(!$徽章){
echo无法显示徽章。
} else {
echo $ badges;
}
..继续做任何页面应该做的..

实际上,函数 fopen 本身就是一个例子 - 它会返回


成功返回文件指针资源,或者错误返回FALSE。 / p>






致命错误(使用例外 - try-catch)



当您有一些代码需要执行的代码,因为它正是用户想要的(例如从数据库读取所有新闻并将其显示给用户) ,你可以使用例外。我们来一个简单的例子 - 一个用户访问了他的个人资料,并希望看到他所有的消息(我们假设,现在,它们以纯文本形式存储)。您可能会有以下功能:

  function getMessages($ user){
$ messages = array();
$ f = fopen(messages_ $ user.txt,r);
if(!$ f){
throw new Exception(Can not read messages!);
}
...做一些处理...
return $ messages;
}

使用如下:

 尝试{
..do某些东西..
$ messages = getMessages($ _ SESSION ['user'])) //假设你在$ _SESSION
foreach中存储用户名($ messages as $ msg){
echo $ msg。< br />;
}
} catch(异常$ e){
echo对不起,有一个错误:$ e-> getMessage();
}

现在这可能会派上用场,如果你有一个顶级将执行所有其他代码的脚本。这意味着,例如,在您的 index.php 中,您只需要:

  try {
..执行一些代码,执行一些函数..
} catch(异常$ e){
echo对不起,有一个错误:$ e - >的getMessage();
}



不要过度使用异常!



无论你做什么,都不要使用例外来检查你可以恢复的东西。阅读另一个问题(完全信用对于这个,以及其他答复者,Anton Gogolev对于这个非常好的解释),为什么会这样。



进一步阅读



现在没有更好的方法来学习如何处理错误,而不是尝试几件事情,看看有什么对你有好处。您可能会发现以下有用的:





希望这有帮助:)


Right now my pages look something like this:

if($_GET['something'] == 'somevalue')
{
    $output .= 'somecode';

    // make a DB query, fetch a row
    //...
    $row = $stmt->Fetch(PDO::ASSOC);

    if($row != null)
    {
        $output .= 'morecode';

        if(somethingIsOK())
        {
            $output .= 'yet more page output';
        }
        else
        {
            $error = 'something is most definitely not OK.';
        }
    }
    else
    {
        $error = 'the row does not exist.';
    }
}
else
{
    $error = 'something is not a valid value';
}

if($error == '') // no error
{
    //display $output on page
}
else // an error
{
    // display whatever error occurred on the page
}

The way I'm doing things works, but it's very cumbersome and tedious for what is probably obvious: suppose that I call a function somewhere in the middle of my code, or want to check the value of a variable, or verify a DB query returned a valid result, and if it fails I want to output an error? I would have to make another if/else block and move all of the code inside the new if block. This doesn't seem like a smart way of doing things.

I have been reading about try/catch and have been thinking of putting all of my code inside a try statement, then let the code run sequentially without any if/else blocks and if something fails just throw an exception. From what I've read, that would halt the execution and make it jump straight to the catch block (just as a failed if statement will go to the else block), where I could then output the error message. But is that an acceptable or standard practice?

What's the best way of handling errors, fatal or not, in a php application that builds and outputs an HTML page? I don't want to just die with a blank screen, as that would be very user un-friendly, but instead want to output a message in the body of the page, still allowing the header and footer to show.

Thanks for your advice!

解决方案

There are a lot of ways that you can deal with this and frankly none of them is intrinsically 'right'.

You will have to decide for yourself, which method is more 'comfortable' for you - it's always a mater of preferences (although there are certain techniques you should avoid and for good reasons).

It will highly depend on how you split your logic, however I tend to enclose all code that can return non-fatal errors inside a function, and use a return value of said function to indicate there was an error.

For fatal errors I tend to use exceptions (with try-catch blocks).

Now just to be clear:

  • A non-fatal error is an error that you can recover from - meaning that even though something went wrong, there is still some code that can be executed and generate some valuable output. For example if you wanted to get current time using NTP protocol, but the server didn't respond, you can decide to use local time function and still display a some valuable data to the user.
  • A fatal error is an error that you would not be able to recover from - meaning that something really bad happened and the only thing you can do is tell your user that page cannot do what it was asked to. For example if you were fetching some data from your database and got SQL Exception - there is no valuable data to be shown and you can only inform the user of this.

Non-Fatal Errors (using function return)

A good example of using function-returns as a way of dealing with non-fatal problems would be a function that is trying to display content of some file on the page when this is not the main objective of the page (for example you would have a function that displays badges, fetched from a text file, on every single page - I know that this is far fetched but bear with me).

function getBadge($file){
    $f = fopen($file,'r');
    if(!$f){
        return null;
    }
    .. do some processing ..
    return $badges;
}

$badges = getBadges('badges.txt');
if(!$badges){
    echo "Cannot display badges.";
} else {
    echo $badges;
}
.. carry on doing whatever page should be doing ..

In fact, the function fopen itself is an example of this - it will return.

Returns a file pointer resource on success, or FALSE on error.


Fatal-Errors (using exceptions - try-catch)

When you have some piece of code that needs to be executed because it's exactly what the user wanted (for example reading all news from database and displaying them to the user), you could use exceptions. Let's take a simple example - a user visited his profile and wanted to see all the messages he's got (let's assume, for now, that they are stored in plain text). You might have a function like:

function getMessages($user){
    $messages = array();
    $f = fopen("messages_$user.txt","r");
    if(!$f){
        throw new Exception("Could not read messages!");
    }
    ... do some processing ...
    return $messages;
}

And use it like this:

try{
    ..do some stuff..
    $messages = getMessages($_SESSION['user'])); //assuming you store username in $_SESSION
    foreach($messages as $msg){
        echo $msg."<br/>";
    }
} catch(Exception $e){
    echo "Sorry, there was an error: ".$e->getMessage();
}

Now this could come in handy, if you had a 'top-level' script that would execute all the other code. That means that, for example, in your index.php you would just have:

try{
    .. execute some code, perform some functions ..
} catch(Exception $e){
    echo "Sorry, there was an error: ".$e->getMessage();
}

Do not overuse exceptions!

Whatever you do, never use exceptions as a way to check something you can recover from. Have a read on another question(full credit goes to Anton Gogolev for a very good explanation on this, as well as other answer-ers) as to why this is the case.

Further reading

Now there is no better way to learn how to deal with errors than to try several things and see what is good for you. You might find the below useful:

Hope this helps :)

这篇关于在PHP页面上处理错误的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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