Laravel 抛出自定义 ValidationException

Jac*_*pia 1 php laravel laravel-5

我正在尝试抛出自定义异常。该项目是一个使用 Google Places API 的 API,如果结果状态为ZERO RESULTS我需要抛出验证异常。这是因为存储的数据是错误的。

为了更清楚这一点。注册用户修改他的个人资料,包括地址、邮政编码等。然后我们有一个 get 方法,我们在其中查询地点 API,这是为了获取纬度和经度并将其添加到个人资料模型中。

if (strcmp($status, 'ZERO_RESULTS') == 0 || strcmp($status, 'INVALID_REQUEST') == 0) {
    $error = ValidationException::withMessages([
        "one_thing" => ["Validation Message #1"], "another_thing" => ['Validation Message #2']
    ]);
    throw $error;
}
Run Code Online (Sandbox Code Playgroud)

我在 StackOverflow 上阅读了一些答案,我什至正在尝试这些答案,但我只收到以下错误:

{
  "errors": [
    {
      "status": 500,
      "code": 1,
      "source": {
        "pointer": "ErrorException line 73 in /Users/jacobotapia/Documents/Espora/one-mind-backend/vendor/sfelix-martins/json-exception-handler/src/ValidationHandler.php"
      },
      "title": "errorexception",
      "detail": "Undefined index: one_thing"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

另外我想指出所有过程都发生在一个GET方法中。

我唯一想要的是返回一个错误,指出我们无法从谷歌地点 API 获得任何结果。这是为了向客户说明用户在应用程序中注册的个人资料数据是错误的。

我究竟做错了什么?

Pra*_*ahu 5

如果您有字段名称“one_thing”和“another_thing”,您可能想尝试一下

$error = Illuminate\Validation\ValidationException::withMessages([
        "one_thing" => ["Validation Message #1"], 
        "another_thing" => ['Validation Message #2']
    ]);

throw $error;
Run Code Online (Sandbox Code Playgroud)

检查 withMessages() 方法定义

 public static function withMessages(array $messages)
    {
        return new static(tap(ValidatorFacade::make([], []), function ($validator) use ($messages) {
            foreach ($messages as $key => $value) {
                foreach (Arr::wrap($value) as $message) {
                    $validator->errors()->add($key, $message);
                }
            }
        }));
    }
Run Code Online (Sandbox Code Playgroud)

键被视为字段名称,因此您将通过的 $errors 将与相应的字段相关。

所以基本上喜欢

$error = \Illuminate\Validation\ValidationException::withMessages([
   'field_name_1' => ['Validation Message for field name 1'],
   'field_name_2' => ['Validation Message for field name 2'],
   'field_name_3' => ['Validation Message for field name 3'],
]);
throw $error;
Run Code Online (Sandbox Code Playgroud)

尝试这个

表格代码是

<form action="{{ route('test-validation') }}" method="POST">
    @csrf
    <input type="text" name="test" value="" />
    @if( $errors->has('test') ) 
        @foreach( $errors->get('test') as $err ) 
            {{ $err  }} 
        @endforeach 
    @endif
    <input type="submit" name="submit" value="Submit" />
 </form>
Run Code Online (Sandbox Code Playgroud)

并在您的路线/web.php

use Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
Route::post('test-validation', function(Request $request){

    $fields = array('test' => $request->input('test'));
    $rules = array('test' => 'required|min:5');

    $validator = Validator::make($fields, $rules); // Empty data and rules fields
    $validator->errors()->add('test', 'This is the error message for test field');
    throw new ValidationException($validator);

    redirect()->withErrors($validator);
})->name('test-validation');
Run Code Online (Sandbox Code Playgroud)

使用此代码,您应该能够正确获取错误。