Laravel 修改驗證異常的響應格式

Laravel 默認驗證不經過後響應格式以下,有時此格式並不知足本身要求,須要修改格式。php

// status 422
{
    "message":"The given data was invalid.",
    "errors":{
        "url":[
            "url 無效的格式"
        ]
    }
}

當 Request 驗證失敗時會拋出 ValidationException異常,最終交由全局異常Handler類處理。Handler繼承自Illuminate\Foundation\Exceptions\Handler,框架中的Handler類調用render處理異常並進行響應,針對於ValidationException異常又調用了convertValidationExceptionToResponse方法來處理。代碼laravel

protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
    if ($e->response) {
        return $e->response;
    }

    return $request->expectsJson()
                ? $this->invalidJson($request, $e)
                : $this->invalid($request, $e);
}

expectsJson()區分是 ajax 請求仍是表單請求,而後分別作處理。git

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
        'message' => $exception->getMessage(),
        'errors' => $exception->errors(),
    ], $exception->status);
}

追蹤到invalidJson(),發現他就是用來處理參數驗證異常響應格式的方法。在App\Exceptions\Handler類中,重寫invalidJson()方法便可。github

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
        'code' => 0,
        'data' => $exception->errors(),
    ], $exception->status);
}

最終,驗證失敗的響應格式以下ajax

// status 422
{
    "code": 0,
    "data":{
        "url":[
            "url 無效的格式"
        ]
    }
}
相關文章
相關標籤/搜索