如果我在请求规则中包含异常,则会出现不同的错误消息

Different error message if I include an exception in Request rules

我的模型有以下更新功能:

public function update(PartnerRequest $request, $id)
{
    $partner = Partner::findOrFail($id);

    if(!$partner -> update($request->all())) {
        throw new HttpException(500);
    }

    return response()->json([
            'status' => 'ok'
        ], 201);

}

这里是请求文件:

namespace App\Api\V1\Requests;

use Config;
use Dingo\Api\Http\FormRequest;

class PartnerRequest extends FormRequest
{
    public function rules()
    {
        return [
               'name' => 'required|unique:partners,' . $this->id . ',id',
               'email' => 'email'    
        ];
    }

    public function authorize()
    {
        return true;
    }
}

如果我删除规则中的例外并将其设为 'name' => 'required|unique:partners',则在重复输入的情况下会出现以下错误消息:

{
  "error": {
    "message": "422 Unprocessable Entity",
    "errors": {
      "name": [
        "The name has already been taken."
      ]
    },
    "status_code": 422
  }
}

但问题出在补丁上,我无法更新模型(由于唯一名称规则)。所以,我需要例外。但是,如果我包含它,而不是上面的特定错误,我有一个像这样的通用错误:

  "error": {
    "message": "SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: partners.name (SQL: update \"partners\" set \"name\" = test, \"updated_at\" = 2017-03-03 10:47:53 where \"id\" = 3)",
    "code": "23000",
    "status_code": 500
  }
}

路线:

$api->post('partner/store', 'App\Api\V1\Controllers\PartnerController@store');
$api->get('partner/all', 'App\Api\V1\Controllers\PartnerController@index');
$api->get('partner/{id}', 'App\Api\V1\Controllers\PartnerController@show');
$api->patch('partner/{id}', 'App\Api\V1\Controllers\PartnerController@update');

您可以尝试做类似的事情:

public function rules()
{
    switch ($this->method()) {
        case 'POST':
            return [
                'name' => 'required|unique:partners',
                'email' => 'email'
            ];
        case 'PUT':
        case 'PATCH':

        return [
            'name' => 'required|unique:partners,name,' . $this->route('id') . ',id',
            'email' => 'email'
        ];
    }
}

希望对您有所帮助!