laravel 如何在 Laravel4 中使用 withErrors 和异常错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18367769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use withErrors with Exception error messages in Laravel4?
提问by Roseann Solano
Assume that I have this Exception Message
假设我有这个 Exception Message
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
echo 'Login field is required.';
}
How can I pass this message Login field is requiredusing withErrors()
?
如何传递此消息 需要使用登录字段withErrors()
?
return Redirect::to('admin/users/create')->withInput()->withErrors();
回答by giannis christofakis
return Redirect::to('admin/users/create')
->withInput()
->withErrors(array('message' => 'Login field is required.'));
回答by Gravy
This depends on where you are catching the exception.
这取决于您在哪里捕获异常。
Sentry does not use the Validator class. So if you want to return an error message the Laravel way, you should create a separate Validator object and validate first, then only pass to Sentry after your validation has passed.
Sentry 不使用 Validator 类。因此,如果您想以 Laravel 的方式返回错误消息,您应该创建一个单独的 Validator 对象并首先进行验证,然后在您的验证通过后才传递给 Sentry。
Sentry will only be able to pass 1 error back as it is catching a specific exception. Furthermore, the error will not be of the same type as the error in the validation class.
Sentry 只能将 1 个错误传回,因为它正在捕获特定的异常。此外,错误将与验证类中的错误类型不同。
Also, if Sentry does catch the exception, then your Validation is clearly not working.
此外,如果 Sentry 确实捕获了异常,那么您的验证显然不起作用。
Code below is not how you should do it, but more to show a combination of what I believe shows ways of working with Laravel / Sentry
下面的代码不是你应该怎么做,而是更多地展示了我认为展示了使用 Laravel / Sentry 的方式的组合
Example User model
示例用户模型
class User extends Eloquent {
public $errors;
public $message;
public function registerUser($input) {
$validator = new Validator::make($input, $rules);
if $validtor->fails() {
$this->errors = $validator->messages();
return false;
}
try {
// Register user with sentry
return true;
}
catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
{
$this->message = "failed validation";
return false;
}
}
}
}
UserController
用户控制器
class UserController extends BaseController {
public function __construct (User $user) { $this->user = $user; }
public function postRegister()
{
$input = [
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation')
];
if ($this->user->registerUser($input)) {
Session::flash('success', 'You have successfully registered. Please check email for activation code.');
return Redirect::to('/');
}
else {
Session::flash('error', $this->user->message);
return Redirect::to('login/register')->withErrors($this->user->errors)->withInput();
}
}