当我扔ValidationException,,manally,,ValidationException,
下面的代码可以解决问题
UserController.php
public function checkEmailExists(Request $request){
try {
$validation = Validator::make($request->only('email'), [
'email' => 'required|email|exists:users,email',
]);
if ($validation->fails()) {
throw (new ValidationException($validation));
}
} catch (\Exception $exception){
return $exception->render(); //nothing is returned/displayed
}
}Handler.php
public function render($request, Throwable $exception)
{
dd($exception instanceof Exception);
}在UserController中,我将手动抛出ValidationException ,在Handler.php呈现方法中,我将检查$exception是Exception的一个实例。所以如果我抛出ValidationException manually
dd($exception instanceof Exception); //gives false
但是当我使用UserStoreRequest (FormRequest)时
UserController.php
public function checkEmailExists(UserStoreRequest $request){
//Exception thrown by laravel if validation fails fro UserStoreRequest
}然后在Handler.php render()方法中
dd($exception instanceof Exception); //gives true
他说:-为什么当我用手扔ValidationException的时候,当ValidationException被FormRequest扔出来的时候,它为什么会有不同的行为?
2:-如果手动抛出ValidationException,那么在catch块中将得到以下错误
Error {#3627
#message: "Call to undefined method Illuminate\Validation\ValidationException::render()"
#code: 0
#file: "myproject/app/Http/Controllers/UserController.php"
#line: 33发布于 2022-03-09 16:53:17
dd($exception instanceof Exception); //gives false我确信这是不可能的。Illuminate\Validation\ValidationException直接从Exception扩展而来。您的结果可能与checkEmailExists中的catch块有关。让您知道,您不应该在控制器内捕获这样的异常,因为这就是异常处理程序的目的(app/Exceptions/Handler.php)。
对于您如何使用这种验证,不应该有任何不同的行为,所以让我展示一下您将以何种方式使用这种验证:
在控制器函数中
在控制器内部,您有可用的助手$this->validate(...):
public function index(\Illuminate\Http\Request $request) {
$this->validate($request, [
'test' => 'required|integer'
], [
'test.integer' => 'Some custom message for when this subvalidation fails'
]);
}这会自动抛出一个ValidationException,因此应该由您的异常处理程序来获取。然后,异常处理程序将决定是返回带有验证错误的JSON响应(例如,当使用了头Accept: application/json时),还是向会话返回闪存消息,以便在模板中显示它们。
外部控制器
有时,对在控制器之外运行的东西使用验证非常方便。例如,这些可能是作业或后台任务。在这些情况下,您可以这样称呼它(这基本上是控制器函数中发生的事情):
class SomeLibrary
{
public function doSomething() {
// Quickest way:
\Illuminate\Support\Facades\Validator::make($data, [
'test' => 'required|integer'
])->validate();
// Convoluted way:
// (see your own code in the original post)
}
}这个语法基本上是做同样的事情,同时也抛出一个ValidationException。
立即抛出验证错误
最后,在某些情况下,您希望立即抛出验证异常,而不需要测试任何输入,在这种情况下,您可以使用它来设置错误消息:
throw \Illuminate\Validation\ValidationException::withMessages([
'amount' => 'The amount is not high enough'
]);然后,这将通过异常处理程序遵循相同的路径。
https://stackoverflow.com/questions/71410913
复制相似问题