dongqindan4406 2019-02-16 08:20
浏览 25
已采纳

错误处理可能无法在PHP脚本中工作

I have a PHP script that goes like:-

<?php session_start() ?>

<body>
 <?php 
   try{
      $userId=$_GET['userId'];
   }
   catch(Exception $e){
      $userId=$_SESSION['userId2'];
   }?>

with $userId=$_GET['userId']; this being my line number 23.

I'm loading the script using http://localhost/checkIdAbout.php?all=ALL.

Now clearly my URL doesn't have the value for $userId, so it'll give an error and that's understandable to me. What I don't understand is that why isn't the try-catch block coming into play? I already stored the value for $_SESSION['userId2']. So shouldn't during execution the code jump from try to catch and give me the required value for $userId?

I get the error: Notice: Undefined index: userId in /var/www/html/checkIdAbout.php on line 23 and I just can't get what's wrong. Please help. Thanks!

  • 写回答

1条回答 默认 最新

  • dronthpi05943 2019-02-16 10:53
    关注

    A notice is not an exception.

    You could write a custom handler to convert notices to exceptions:

    set_error_handler(function ($errno , $errstr, $errfile, $errline) {
        if (!(error_reporting() & $errno)) {
            return false;
        }
        throw new ErrorException($errstr, $errno, $errno, $errfile, $errline);
    }, E_NOTICE);
    
    try {
        $foo++;
    } catch (ErrorException $e) {
        echo 'Notice cast to exception: '. $e->getMessage(), PHP_EOL;
    }
    

    ... but it's normally a bad idea because throwing an exception interrupts the script flow until next catch (or totally aborts the script if none). And, in this case, I don't think it's justified to intentionally cause a notice just to be able to use exception handling, when there're simpler alternatives, e.g.:

    $userId = filter_input(INPUT_GET, 'userId') ?? $_SESSION['userId2'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C语言PE文件遍历节表
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥50 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码