duanrang9348 2013-03-13 07:48
浏览 71
已采纳

用户友好的PHP尝试捕获

Since a short period of time I'm working with Try Catch in PHP. Now, every time a new error is thrown you get a fatal error on the screen, this isn't really user friendly so I was wondering if there's a way to give the user a nice message like an echo instead of a fatal error.

This is the code I have now:

public static function forceNumber($int){
    if(is_numeric($int)){
        return $int;
} else {
        throw new TypeEnforcerException($int.' must be a number');
}
}

public function setStatus($status) {
    try {
        $this->status = TypeEnforcer::forceInt($status); 
    } catch (TypeEnforcerException $e) {
        throw new Exception($e->getMessage());
    } catch (Exception $e) {
        throw new Exception($e->getMessage());
    }

}
  • 写回答

1条回答 默认 最新

  • duanlongling5308 2013-03-13 08:00
    关注

    This is best solved with a frontend controller that is able to catch all uncatched exceptions:

    <?php
    require('bootstrap.php');
    
    try {
        $controllerService->execute($request);
    } catch (Exception $e) {
        $controllerService->handleControllerException($e);
    }
    

    You can then write code to return the internal server error because an exception signals an exceptional case so it normally is an 500 internal server error. The user must not be interested what went wrong other than it just didn't work out and your program crashed.

    If you throw exceptions to give validation notices you need to catch those in a different layer (and you're probably doing it wrong if you use exceptions for that).


    Edit: For low-level functions, because PHP is loosely typed, if a function expects and int, cast to intDocs:

    public static function forceNumber($int){
        $int = (int) $int;
        return $int;
    }
    

    this will actually force the integer. In case the cast is not possible to do (e.g. $int it totally incompatible) PHP will throw the exception for you.

    The example is a bit akward because by the method's name you use it to validate some number and provide an error if not (here wrongly with an exception). Instead you should do some validation. If you expect wrong input, it's not an exceptional case when wrong input is provided, so I would not use exceptions for that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line