【问题标题】:Laravel throw a custom ValidationExceptionLaravel 抛出一个自定义的 ValidationException
【发布时间】:2019-10-20 13:44:13
【问题描述】:

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

为了更清楚地说明这一点。注册用户修改他的个人资料,包括地址、邮政编码等。 然后我们有一个 get 方法,在该方法中我们对 places 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;
}

我在 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"
    }
  ]
}

我还想指出,所有过程都发生在GET 方法期间。

我唯一想要的是返回一个错误,指出我们无法从 google 地方 API 获得任何结果。这样做的目的是告诉客户,用户在应用中注册的个人资料数据是错误的。

我做错了什么?

【问题讨论】:

  • 您想要什么实际响应?我们无法理解,您想要正确的验证状态码吗?
  • 我更新了问题,我希望这能澄清疑问
  • @JacoboTapia 你有字段名 'one_thing' 和 'another_thing' 吗?
  • 不,这是一个 GET 方法。该请求有任何参数
  • keys 中的 withMessages 方法应该是字段名称。

标签: php laravel laravel-5


【解决方案1】:

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

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

throw $error;

检查 withMessages() 方法definition

 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);
                }
            }
        }));
    }

键被视为字段名称,因此您将通过的 $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;

试试这个

表格代码是

<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>

在你的 routes/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');

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

【讨论】:

  • 现在我在 POST 请求中有类似的字段,但它不起作用
  • @JacoboTapia 我已经用示例代码更新了我的答案,请检查它是否能让你更好地了解它。
【解决方案2】:

这是您问题的解决方案

解决方案 1:使用 http 代码发送错误消息

return response()->json(["error"=> "YOUR_MESSAGE_HERE"],401);

Laravel - Return json along with http status code

【讨论】:

  • 这不起作用:"title": "badmethodcallexception", "detail": "Method Illuminate\\Http\\JsonResponse::toArray does not exist."
  • 你用的是哪个版本的 laravel?
  • 用 laravel 和你的 php 版本更新你的问题。
猜你喜欢
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2014-09-12
  • 2011-10-06
相关资源
最近更新 更多