doujiao7679 2013-05-29 18:47
浏览 262

检测是否在不使用自定义异常类的情况下手动抛出异常

I got a try-catch block in my php application like this:

try {
  if ($userForgotToEnterField) {
     throw new Exception('You need to fill in your name!');
  }
  ...
  doDifferentThingsThatCanThrowExceptions();
  ...
} catch (ExpectedException $e) {
  $template->setError('A database error occured.');
} catch (Exception $e) {
  $template->setError($e->getMessage());
}

I would like to only output $e->getMessage() for the exceptions I have manually thrown with a custom error text and not the ones that have been thrown by the other code as these might contain sensitive information or very technical info that the user should not see.

Is it possible to differentiate from a manually thrown exception and a random exception thrown by some method without using a custom exception class?

  • 写回答

2条回答 默认 最新

  • 普通网友 2013-05-29 19:01
    关注

    I've thought about this a bit and I'd say that what you are doing DOES call for a custom exception class. If you want to get around it (which in the end is going to be more confusing), you would basically create a global (or same-scope) variable that all exceptions can modify, and in your throw block flag it.

    $threwCustomException = false;
    
    try {
      if ($userForgotToEnterField) {
         throw new Exception('You need to fill in your name!');
         $threwCustomException = true;
      }
      ...
      doDifferentThingsThatCanThrowExceptions();
      ...
    } catch (ExpectedException $e) {
      $template->setError('A database error occured.');
    } catch (Exception $e) {
        if($threwCustomException){
            //Whatever custom exception handling you wanted here....
        }
      $template->setError($e->getMessage());
    }
    

    That's the best I can think of. However, this is a bad idea, and it's the whole reason you are allowed to create your own exception classes. I know you're not looking for this answer, but since you look like you're trying not to create a TON of extra code, I would just extend Exception to "CustomException" or some other name specific to your project, and throw that for all cases, and handle it that way. Hope that helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch