try / catch PHP不捕获异常(laravel控制器)

时间:2019-06-27 18:10:11

标签: php laravel exception

我正在与Laravel合作,并尝试像对Java一样使用try / catch。不幸的是,它无法按预期方式工作...没有捕获到该异常,并且它没有返回错误消息,而是发出了422异常。

这是我的功能:

None

我这样称呼这个方法

public function changePassword(Request $request){

        try{
            if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {
                return "Your current password does not matches with the password you provided. Please try again.";
            }

            if(strcmp($request->get('currentpassword'), $request->get('new-password')) == 0){
                return "New Password cannot be same as your current password. Please choose a different password.";
            }

            $validatedData = $request->validate([
                'currentpassword' => 'required',
                'newpassword' => 'required|string|min:6',
            ]);

            $user = Auth::user();
            $user->password = bcrypt($request->get('newpassword'));
            $user->save();

            return "Password changed successfully !";
        }
        catch(Exception $error){
            return $error->getMessage();
        }
   }

在这里,我想获取我的异常消息并显示它。取而代之的是,我在使用请求时遇到了错误,并且没有捕获到该异常

  

422无法处理的实体   {“ message”:“给定的数据无效。”,“ errors”:{“ newpassword”:[“ newpassword必须至少包含6个字符。”]}}

非常感谢

5 个答案:

答案 0 :(得分:1)

使用getMessage()方法。例如:-

$error->getMessage();

在catch块中使用它。它将为您工作。享受吧!

答案 1 :(得分:1)

您可以尝试

public function changePassword(Request $request){

        try{
            if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {
                return "Your current password does not matches with the password you provided. Please try again.";
            }

            if(strcmp($request->get('currentpassword'), $request->get('new-password')) == 0){
                return "New Password cannot be same as your current password. Please choose a different password.";
            }

            $validatedData = $request->validate([
                'currentpassword' => 'required',
                'newpassword' => 'required|string|min:6',
            ]);

            $user = Auth::user();
            $user->password = bcrypt($request->get('newpassword'));
            $user->save();

            return "Password changed successfully !";
        }
        catch(\Exception $error){
            return $error->getMessage();
        }
   }

答案 2 :(得分:1)

您的错误处理代码正确。捕获异常的代码是在PHP中实现的方式,并且其工作方式与Java(我都对二者进行了编码)相同。简而言之,您的代码没有错。

我的猜测是两件事之一,但我不确定两者之一:

1)您正在OSX上进行测试,并且某些东西大量嵌套时,某些XDebug设置可能会导致错误处理问题(我个人在迁移中就曾经历过)。 SO XDebug settings problem

2)Laravel有一个拦截器,可以在错误发生时捕获该错误,并且该处理程序已被注入以优先于您的处理程序。 SO form validation exception not catching

希望这会在正确的方向上推动您。抱歉,这是非答案类型的答案。

答案 3 :(得分:1)

Laravel验证失败不会引发异常!因此,您无法捕获...。如果要捕获,请使用如下所示的自定义验证并自己引发异常

public function changePassword(Request $request)
{
    try
    {
       $data['currentpassword'] = $request->get('currentpassword');
       $data['newpassword'] = $request->get('newpassword');
        if (!(Hash::check($request->get('currentpassword'), Auth::user()->password))) {
            $message['currentpassword.required'] = "Your current password does not matches with the password you provided. Please try again.";
            $data['currentpassword'] = ""; // I used for required rule as a example , but I recommend to create custom rule for this
        }

        if(strcmp($request->get('currentpassword'), $request->get('new-password')) == 0){
            $message['newpassword.required'] = "New Password cannot be same as your current password. Please choose a different password.";
            $data['newpassword'] = "";// I used for required rule as a example , but I recommend to create custom rule for this
        }

        $rule = [
            'currentpassword' => 'required',
            'newpassword' => 'required|string|min:6',
        ];
        $validatedData = \Illuminate\Support\Facades\Validator::make($data, $rule, $message);
        if($validateData->fails()) {
           throw new \Exception($validateData->messages());
        }

        $user = Auth::user();
        $user->password = bcrypt($request->get('newpassword'));
        $user->save();

        return "Password changed successfully !";
    }
    catch(Exception $error)
    {
        return $error->getMessage();
    }
}

答案 4 :(得分:1)

您要在哪里返回$ error,可以在view()中返回$ error或使用redirect()或response()等...

示例:

return back()->back()->withError($error->getMessage())->withInput();

另一个例子:

return response()->json('error_message' => $error->getMessage());

希望您能明白。

在刀片视图中,您可以显示$ error消息,如下所示:

@if (session('error'))
    <div class="alert alert-danger" style="margin-top: 0.2rem;">
        {{ session('error') }}
    </div>
@endif