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.

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

报告相同问题?

悬赏问题

  • ¥20 阿里云python代码求解
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路