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

时间:2017-04-27 20:06:31

标签: php laravel exception-handling laravel-5.4

我有一个应用程序,对于每个方法,它在进行代码执行之前进行字段验证。

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

有人可以帮助我吗?

1 个答案:

答案 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);
}
@Samsquanch是对的,您展示的用例示例很简单,只需从控制器返回JSON就更好了。但是,如果您从其他类中抛出异常,这将是有意义的。