Home > Blockchain >  How to set an exception in laravel
How to set an exception in laravel

Time:11-18

I made a global helper function to avoid typos for database statuses

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;
    }

}

However, I want the code to scream at me every time I input an incorrect parameter in debug mode. how can I do that?

CodePudding user response:

Just throw the exception when no situation is valid

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');
}

I would suggest you change your code to

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');
    }   
}
  • Related