如何在PHP中抛出新的Exception()中传递数组。在异常处理程序中传递数组的最佳可能性是什么?

时间:2017-08-26 03:52:38

标签: php arrays laravel exceptionhandler

这是我的代码,但它发送给我错误。它表示异常处理程序的错误参数。

   try {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'email_address' => 'required|unique:users|email',
            'username' => 'required|unique:users|max:20',
            'phone_number' => 'alpha_num|max:13',
            'password' => 'required|min:6|max:18',
        ]);


        if ($validator->fails()) {
            throw new Exception('Please checkout your fields again!', $validator->errors() );
        }

    }catch( Exception $e){
        return ['success'=>false, 'message'=>$e->getMessage()];
    }

2 个答案:

答案 0 :(得分:0)

您可以使用implode函数将数组作为字符串加入


这样的事情:

try {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'email_address' => 'required|unique:users|email',
            'username' => 'required|unique:users|max:20',
            'phone_number' => 'alpha_num|max:13',
            'password' => 'required|min:6|max:18',
        ]);


        if ($validator->fails()) {
            throw new Exception('Please checkout your fields again!', implode(',',$validator->errors()) );
        }

    }catch( Exception $e){
        return ['success'=>false, 'message'=>$e->getMessage()];
    }

答案 1 :(得分:0)

您应该尝试这可能对您有所帮助:

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'email_address' => 'required|unique:users|email',
            'username' => 'required|unique:users|max:20',
            'phone_number' => 'alpha_num|max:13',
            'password' => 'required|min:6|max:18',
        ]);

        if ($validator->fails()) {
            return redirect('yourRoute')
                        ->withErrors($validator)
                        ->withInput();
        }

有关详情,请按此this question