pezo's avatar
Level 2

HTTP/1.1 422 Unprocessable Entity JSON render problem

Hi all, I'm developing a REST API using Transformers and JSON responses. I want to render proper error messages as jsonapi.org recommended.

My app/Exceptions/Handler.php render() method:

    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }

        $status = 500;
        $title  = 'General error';
        $detail = 'Sorry, something unthinkable happened now';

        switch($e){
            case ($e instanceof NotFoundHttpException):
                $status = 404;
                $title = 'The requested resource has not been found';
                $detail = '';
                break;
            case ($e instanceof MethodNotAllowedHttpException):
                $status = 405;
                $title = "Method not allowed exception";
                $detail = "The HTTP method '{$request->getMethod()}' is not allowed here";
                break;
            case ($e instanceof UnprocessableEntityHttpException):
                $status = 422;
                $title = "Unprocessable Entity";
                $detail = "We're sorry, we can not process your data what you've just sent to us";
                break;
        }

        return response()->json([
            'errors' => [
                [
                    'status'    => $status,
                    'source'    => ['pointer' => $request->getUri()],
                    'title'     => $title,
                    'detail'    => get_class($e)
                ]
            ]
        ], $status);
        
        return parent::render($request, $e);
    }

The NotFoundHttpException returns proper error as expected:

{
  "errors": [
    {
      "status": 405,
      "source": {
        "pointer": "http:\/\/localhost:8001\/api\/v1\/df\/documents"
      },
      "title": "Method not allowed exception",
      "detail": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException"
    }
  ]
}

The problem is I can not catch validation errors like UnprocessableEntityHttpException, I get this back:

{
  "data.type": [
    "The data.type field is required."
  ]
}

How can I handle/transform all my exceptions to a proper JSON response?

0 likes
1 reply
pezo's avatar
Level 2

The problem is that Request validation does not throw exceptions, it renders the response directly.

From the documentation: "If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors."

How can I deal with this situation? Any help will be appreciated.

Please or to participate in this conversation.