Laravel中的自定义异常处理程序

I have an application, which for each method it does a field validation before proceeding with code execution.

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

I needed to pass the object to the CustomFieldValidation class to pass to the Laravel Handler class to handle the errors and return in the JSON form. How to do this?

class CustomFieldValidation extends \Exception
{
    public function __construct($validator,$message= NULL, $code = NULL, Exception $previous = NULL)
    {
        parent::__construct($message, $code, $previous);
    }

}

I was hoping to manipulate the message handler's rendering method.

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

Can someone help me?

To answer your question: just add a $validator attribute to your exception class.

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

@Samsquanch is right, the use case example you're showing is simple and it'd be better to just return JSON from the controller. However if you're throwing the exception from some other class, this would make sense.