Laravel modification verification exception response format example code details

Time:2020-9-26

The default response format of larravel is as follows. Sometimes this format does not meet its own requirements and needs to be modified.

// status 422
{
 "message":"The given data was invalid.",
 "errors":{
  "url":[
   "Invalid URL format"
  ]
 }
}

Thrown when the request fails validationValidationExceptionException, which is finally handed over to the global exceptionHandlerClass processing.HandlerInherited fromIlluminate\Foundation\Exceptions\Handler, in the frameworkHandlerClass callrenderHandle and respond to exceptions forValidationExceptionException called againconvertValidationExceptionToResponseMethod. code


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

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

expectsJson()Distinguish whether it is an Ajax request or a form request, and then do the processing separately.


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

Trace toinvalidJson()It is found that it is the method used to process parameter validation exception response format. stayApp\Exceptions\HandlerClass, overrideinvalidJson()Method is enough.


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

Finally, the response format for validation failure is as follows

// status 422
{
 "code": 0,
 "data":{
  "url":[
   "Invalid URL format"
  ]
 }
}

summary

This article on the larvel modification verification exception response format code detailed article introduced here, more related to the content of the larevel exception response format, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!