當我ValidationException 手動拋出和laravel 從 FormRequest 拋出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
1:- 為什么當我手動拋出 ValidationException 和 laravel 從 FormRequest 拋出 ValidationException 時它有不同的行為?
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
uj5u.com熱心網友回復:
dd($exception instanceof Exception); //gives false
我很確定這是不可能的。Illuminate\Validation\ValidationException直接從 延伸Exception。您的結果可能與checkEmailExists. 如您所知,您不必在控制器中捕獲此類例外,因為這就是例外處理程式 ( 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.
立即拋出驗證錯誤
Lastly, in some cases you want to immediately throw a validation exception without even needing to test any input, in that case you can use this to set the error messages:
throw \Illuminate\Validation\ValidationException::withMessages([
'amount' => 'The amount is not high enough'
]);
This will then follow the same route through the exception handler.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442960.html
標籤:php 拉拉维尔 laravel-5 laravel-8 laravel 异常
上一篇:自定義ListviewsetonItemClickListner在DialogFragment中使用kotlin中的Viewbinding不起作用
