zoukankan      html  css  js  c++  java
  • 如何让你的服务器永远不抛出500

    写代码原则:

    1、对于mysql或者redis等其他以扩展形式接入的一定 basemodel 处要用捕获异常,可以捕获错误并不至于脚本直接终止 - 比如mysql的column not found 或者data tool long或者invalid number for datetime

    2、对于数组下标一定以empty校验以防止出现undefined offerset直接终止脚本

    3、

    PHP常见错误:

    1、调用function参数错误

    array_merge([1,2,3],''); -- Warning: array_merge(): Expected parameter 2 to be an array, string given

    2、类不存在

    Fatal error: Uncaught Error: Class 'test' not found

    3、变量未定义

    PHP Notice:  Undefined variable

    4、数组无匹配下标

    PHP Notice:  Undefined index: abc 

    5、数据库入库错误

    column not found
    data too long for name
    Invalid datetime format: 1292 Incorrect datetime value: '111' for column 'update_time' at row 1

    常用的捕获错误方法:

    1、try catch捕获数据库错误

    try {
        $TalentModelObj->update($talentInfo,array(['id','=',$talentId]));
        return array('retcode'=>StatusCode::$SUCCESS,'data'=>$talentId,'msg'=>'编辑候选人信息成功');
    } catch (Throwable $th) {
        return array('retcode'=>StatusCode::$ERROR,'data'=>$th,'msg'=>'编辑失败,错误信息:'.json_encode($th));
    }

    2、注册错误回调函数捕获错误

    // 设定报错级别为全部
    error_reporting(E_ALL);
    // set_error_handler — 设置用户自定义的错误处理函数
    set_error_handler([__CLASS__, 'appError']);
    // set_exception_handler — 设置用户自定义的异常处理函数
    set_exception_handler([__CLASS__, 'appException']);
    // register_shutdown_function — 注册一个会在php中止时执行的函数,脚本执行完成或者 exit() 后被调用
    register_shutdown_function([__CLASS__, 'appShutdown']);

    1、调用方法参数错误 - 可以用try catch捕获到

    function e($a){
        return $a;
    }
    try {
        $a = e();
    } catch (Throwable $th) {
        print_r($th);
    }

    2、直接输出未定义变量 - 脚本会异常终止 - 只能用 register_shutdown_function 注册函数回调记录异常信息

    // 无法捕获异常
    try
    { echo $c; } catch (Throwable $th) { print_r($th); }

    3、数据库错误(列未定义、字段过长等)都可以用try catch捕获错误并返回

    4、数组无下标会导致运行终止,只能用 shutdown 回调捕获错误

    // 无法捕获错误
    try
    { $a = array(123); echo $a['abc']; } catch (Throwable $th) { print_r($th); }

     5、数组转int不会抛出异常,但是转字符串会


    1、判定数字用:

    is_numeric
  • 相关阅读:
    MySQL日期比较
    MySQL日期函数、时间函数总结(MySQL 5.X)
    MySQL日期、字符串、时间戳互转
    通过 zxing 生成二维码
    前台时间格式 2019-03-09T16:00:00.000Z
    基于vue-cli配置手淘的lib-flexible + rem,实现移动端自适应
    python爬虫实例大全
    python3 BeautifulSoup模块使用
    Python 通过sgmllib模块解析HTML
    如何搭建一个合理的数值框架?
  • 原文地址:https://www.cnblogs.com/xuweiqiang/p/11758097.html
Copyright © 2011-2022 走看看