【问题标题】:How can I run from exception and receive false in this case在这种情况下,如何从异常中运行并接收错误
【发布时间】:2018-09-23 04:09:58
【问题描述】:

我有这个代码

 function checkIBAN($iban)
{
    $iban = strtolower(str_replace(' ','',$iban));
    $Countries = array('al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24);
    $Chars = array('a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35);

    try{
        $cntr=(in_array(substr($iban,0,2),$Countries)) ? $Countries[substr($iban,0,2)] : false;
    if(strlen($iban) == $cntr){
        $MovedChar = substr($iban, 4).substr($iban,0,4);
        $MovedCharArray = str_split($MovedChar);
        $NewString = "";
        foreach($MovedCharArray AS $key => $value){
            if(!is_numeric($MovedCharArray[$key])){
                $MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
            }
            $NewString .= $MovedCharArray[$key];
        }
        if(bcmod($NewString, '97') == 1)
        {
            return TRUE;
        }
        else{
            return FALSE;
        }
    }
    else{
        return FALSE;
    }
    }catch (Exception $e) {
        report($e);
        return false;
    }

}

我在 Laravel 中收到了这个异常

{消息:“未定义的偏移量:21”,异常:“ErrorException”,...} 例外 : “错误异常” 此字符串中的“未定义偏移量:21”$Countries[substr($iban,0,2)]

在这种情况下,我怎样才能从 Exception 中运行并只收到一个 false?由于这个事实,我正在检查 iban 的函数必须只接收 true 或 false 而不是异常。如果我在 Ajax 中收到 500error 的异常

【问题讨论】:

    标签: laravel custom-errors


    【解决方案1】:

    packagist 上有很多经过测试的 iban 验证库。 https://packagist.org/?q=iban&p=0 我会改用其中之一。

    比从另一个stackoverflow question.复制的一些硬代码要好得多

    “ErrorException”是 laravel 的错误处理程序,将 php 错误转换为异常。您可以通过在执行数组访问之前添加检查来避免错误。

    考虑这个例子:

    $MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
    

    它假定$MovedCharArray 的索引为$key,并假定$Chars 的索引为$MovedCharArray[$key]。如果其中任何一个不存在,您将收到该错误。

    在尝试访问这些数组元素之前添加一些检查,您可以避免错误。

    if(isset($MovedCharArray[$key]) && isset($Chars[$MovedCharArray[$key]])){
      $MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
    }else{
      //Some error condition you'll need to deal with.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 2012-12-16
      • 1970-01-01
      • 2021-06-19
      • 2014-08-24
      • 1970-01-01
      • 2020-05-19
      • 2013-02-20
      相关资源
      最近更新 更多