捕获异常并重定向 [英] Catch exception and redirect

查看:82
本文介绍了捕获异常并重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Laravel应用程序制作安装脚本,并且正在尝试创建管理员帐户作为安装步骤之一.当出现错误时,应用程序应使用警告消息重定向回同一页面,但Laravel显示错误消息并停止应用程序:

I'm making an installation script for a Laravel application and I'm trying to create admin account as one of the installation steps. When an error arises, the application should redirect back to the same page with an alert message, but Laravel shows error message and stops the application:

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检查错误并重定向,如果出现错误以及如何发生?

Is it possible to check for errors using try/catch and redirect if an error arises and how?

推荐答案

Laravel捕获了一些错误,因此为了能够自己处理它们,您需要编辑app/Exceptions/Handler.php,并且也许使用render方法来处理您的错误.自己的例外:

Laravel catches some errors, so to be able to process them yourself, you need to edit the app/Exceptions/Handler.php and, maybe, use the render method to handle your own exceptions:

public function render($request, Exception $e)
{
    if ($result = MyExceptionHandler::handle($e))
    {
        return $result;
    }

    return parent::render($request, $e);
}

这篇关于捕获异常并重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆