假设我有这个Exception Message
catch (CartalystSentryUsersLoginRequiredException $e)
{
echo 'Login field is required.';
}
如何使用withErrors()
传递此消息需要登录字段?
return Redirect::to('admin/users/create')->withInput()->withErrors();
return Redirect::to('admin/users/create')
->withInput()
->withErrors(array('message' => 'Login field is required.'));
这取决于捕获异常的位置。
Sentry不使用Validator类。因此,如果你想以Laravel的方式返回错误消息,你应该创建一个单独的Validator对象并首先进行验证,然后在验证通过后才传递给Sentry。
Sentry在捕获特定异常时只能返回1个错误。此外,该错误的类型与验证类中的错误的类型不同。
此外,如果Sentry确实捕捉到了异常,那么您的验证显然不起作用。
下面的代码不是你应该怎么做,而是更多地展示了我认为展示了使用Laravel/Sentry 的方法的组合
示例用户模型
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 (CartalystSentryUsersLoginRequiredException $e)
{
$this->message = "failed validation";
return false;
}
}
}
}
用户控制器
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();
}
}