【问题标题】:I want to throw a user defined exception for empty json in Laravel我想在 Laravel 中为空 json 抛出用户定义的异常
【发布时间】:2020-05-15 07:10:27
【问题描述】:

我想检查输入的 json 是否存在并相应地返回一条消息。有两种方法可以验证这一点,使用 isset($a) 方法或使用 $request->has('a') 方法。但无论我使用哪种方法,如果我的输入 json 为 null,它都会给出异常“未定义属性:stdClass::$a”。

$input = json_decode(file_get_contents('php://input', true));
    $a = $input->a;

if(isset($a)){
         $response = json_encode(array("response_code"=>200, "response_message"=>"Input present"));
             return $response; 
      } else {
       $response = json_encode(array("response_code"=>150, "response_message"=>"Input absent"));
    return $response; 
                    }

输入 json:{}

【问题讨论】:

    标签: php json laravel if-statement input


    【解决方案1】:

    错误发生在代码中的这一行

    $a = $input->a;
    

    在 isset($a) 检查之前。 尝试像这样重写它:

    $input = json_decode(file_get_contents('php://input', true));
    
    if(isset($input->a)){
        $response = json_encode(array("response_code"=>200, "response_message"=>"Input present"));
        return $response;
    } else {
        $response = json_encode(array("response_code"=>150, "response_message"=>"Input absent"));
        return $response;
    }
    

    【讨论】:

    • 谢谢它真的很有帮助。有没有办法为许多用户输入做到这一点?例如:如果我有以下输入怎么办:a、b、c、d、e、f。那么在这种情况下,是否有任何其他方法,或者我必须为每个输入运行 if case ?
    • 你可以试试 $request->filled() 方法。所以代替“if(isset($input->a)){”尝试“if($request->filled(['a', 'b', 'c', 'd', 'e', 'f '])){".
    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 2016-06-24
    • 2011-05-30
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2014-06-12
    • 2011-10-06
    相关资源
    最近更新 更多