我有一个应用程序,对于每个方法,它在进行代码执行之前进行字段验证。
public function authenticateSeller(Request $request)
{
$fields = $request->all();
$rules = config("validation-rules.loads.access");
$validator = Validator::make($fields, $rules);
if($validator->fails()) {
throw new CustomFieldValidation($validator);
}
}
我需要将对象传递给CustomFieldValidation类以传递给Laravel Handler类来处理错误并返回JSON表单。怎么做?
class CustomFieldValidation extends \Exception
{
public function __construct($validator,$message= NULL, $code = NULL, Exception $previous = NULL)
{
parent::__construct($message, $code, $previous);
}
}
我希望操纵消息处理程序的渲染方法。
public function render($request, Exception $exception)
{
if($exception instanceof CustomFieldValidation) {
foreach($validator->errors()->all() as $message) {
$errors[] = [
'message' => $message,
];
}
return response()->json($errors, 400, ['Content-type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
}
return parent::render($request, $exception);
}
有人可以帮助我吗?
答案 0 :(得分:1)
要回答您的问题:只需在您的例外类中添加$validator
属性。
class CustomFieldValidation extends \Exception
{
public $validator;
public function __construct($validator,$message= NULL, $code = NULL, Exception $previous = NULL)
{
parent::__construct($message, $code, $previous);
$this->validator = $validator;
}
}
public function render($request, Exception $exception)
{
if($exception instanceof CustomFieldValidation) {
foreach($exception->validator->errors()->all() as $message) {
$errors[] = [
'message' => $message,
];
}
return response()->json($errors, 400, ['Content-type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
}
return parent::render($request, $exception);
}