我正在为Laravel应用程序制作安装脚本,我正在尝试创建管理员帐户作为安装步骤之一。出现错误时,应用程序应重定向回带有警报消息的同一页面,但Laravel会显示错误消息并停止应用程序:
public function postAdmin() {
$validation_rules = array(
'username' => 'required|min:4|alpha_dash|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:4',
);
$validator = Validator::make(Input::all(), $validation_rules);
if ($validator->fails()) {
return Redirect::to('install/admin')
->withInput()
->withErrors($validator);
}
else {
try {
$username = Input::get('username');
$email = Input::get('email');
$password = Hash::make(Input::get('password'));
$admin_user = new User;
$admin_user->username = $username;
$admin_user->email = $email;
$admin_user->password = $password;
$admin_user->admin = 1;
$user_data_saved = $admin_user->save();
if ($user_data_saved) {
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')));
return Redirect::to('install/finish')->with('success', "Admin account created");
}
else {
return Redirect::to('install/admin')
->with('error', 'Error adding admin info');
}
}
catch(Exception $e) {
return Redirect::to('install/admin')->with('error', "Error creating admin account");
}
} }
是否可以使用try / catch检查错误并在出现错误时重定向以及如何进行?
答案 0 :(得分:1)
Laravel捕获了一些错误,因此为了能够自己处理它们,您需要编辑app/Exceptions/Handler.php
,并且可能使用render方法来处理自己的异常:
public function render($request, Exception $e)
{
if ($result = MyExceptionHandler::handle($e))
{
return $result;
}
return parent::render($request, $e);
}