Best way to handle errors on a php page?

后端 未结 8 732
傲寒
傲寒 2020-11-30 22:10

Right now my pages look something like this:

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

    // make a DB query, fetch a row
           


        
8条回答
  •  萌比男神i
    2020-11-30 22:47

    This is much more elegant and readable.

    try
    {
    
        if($_GET['something'] != 'somevalue') 
        {
            throw new Exception ('something is not a valid value');
        }
    
    
        $output .= 'somecode';
    
        // make a DB query, fetch a row
        //...
        $row = $stmt->Fetch(PDO::ASSOC);
    
        if($row == null)
        {
            throw new Exception ('the row does not exist.');
        }
    
    
        $output .= 'morecode';
    
    
        if(somethingIsOK())
        {
            $output .= 'yet more page output';
        }
        else
        {
            throw new Exception ('something is most definitely not OK.');
        }
    
    
        echo $output;
    
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
    }
    

提交回复
热议问题