【问题标题】:How to set an exception in laravel如何在 laravel 中设置异常
【发布时间】:2022-11-18 20:04:17
【问题描述】:

我做了一个全局辅助函数来避免数据库状态的拼写错误

function status($status){

    $SUCCESS = 'SUCCESS';
    $ABORTED = 'ABORTED';
    $PENDING = 'PENDING';
    $EXPIRED = 'EXPIRED';

    $status = strtoupper($status);

    if($status === 'S'){
        return $SUCCESS;
    }
    elseif($status === 'A'){
        return $ABORTED;
    }
    elseif($status === 'P'){
        return $PENDING;
    }
    elseif($status === 'E'){
        return $EXPIRED;
    }

}

但是,每次我在调试模式下输入不正确的参数时,我都希望代码对我尖叫。我怎样才能做到这一点?

【问题讨论】:

  • 首先,不清楚你真正想要什么。第二,这些$SUCCESS本地变量没有实际用处。也许 const 会更有意义,但如果那只是针对 status() 那么仍然没用。第三,array map 可能会更干净,除非你喜欢 if/else spaghetti

标签: laravel


【解决方案1】:

没有情况有效时抛出异常

function status($status){

    $SUCCESS = 'SUCCESS';
    $ABORTED = 'ABORTED';
    $PENDING = 'PENDING';
    $EXPIRED = 'EXPIRED';

    $status = strtoupper($status);

    if($status === 'S'){
        return $SUCCESS;
    }
    elseif($status === 'A'){
        return $ABORTED;
    }
    elseif($status === 'P'){
        return $PENDING;
    }
    elseif($status === 'E'){
        return $EXPIRED;
    }
    throw new Exception('invalid status');
}

我建议您将代码更改为

function status($status){
    switch(strtoupper($status)) {
        case 'S':
            return 'SUCCESS';
        case 'A':
            return 'ABORTED';
        case 'P':
            return 'PENDING';
        case 'E':
            return 'EXPIRED';
        default:
            throw new Exception('invalid status');
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2019-02-03
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多