gabogabans
gabogabans

Reputation: 3553

Return custom json response when catching ValidationException

I have a controller entry point where I execute another method from my ProductService inside a try catch block, I pretend to catch all exceptions that may occur inside $this->productService->create() method, except for Validation errors, if it's a validation error $e->getMessage() won't do, since I'll get generic response "Given data was invalid" instead of full custom messages. After reading some, I decided to use render method in laravel Handler class, I added this:

//In order to react to validation exceptions I added some logic to render method, but it won't actually work, I'm still getting normal exception message returned.

public function render($request, Exception $exception)
    {
        if ($request->ajax() && $exception instanceof ValidationException) {
            return response()->json([
                'message' => $e->errors(),
            ],422);
        }
        
        return parent::render($request, $exception);
}

However I'm still getting the default message, this means that my catch block is catching normal exception instead of my custom render method...

In my controller, try catch block looks like this:

try
        {
            $this->productService->create($request);

            return response()->json([
                'product' => $product,
            ], 200);
          
        } 
        //I want to catch all exceptions except Validation fails here, and return simple error message to view as 
        json 
        catch (\Exception $e)
        {
            return response()->json([
                'message' => $e->getMessage(),
            ], $e->getStatus() );
        }

Also, in ValidationException, I cannot use $e->getCode, $e->getStatus(), it will always return 0 or sometimes 1, afaik it should be 422, that's why in my render method I'm manually returning 422. In my try catch block with normal Exceptions $e->getCode() works correctly, why is that?

Upvotes: 1

Views: 1134

Answers (1)

Timmy Iwoni
Timmy Iwoni

Reputation: 109

In your render function, you are referencing an error instance that isn't defined, you have define Exception $exception but you are referencing $e->errors();

You code should be:

public function render($request, Exception $exception)
    {
        if ($request->ajax() && $exception instanceof ValidationException) {
            return response()->json([
                'message' => $exception->errors(),
            ],422);
        }

        return parent::render($request, $exception); 
}

Change $e->errors(); to $exception->errors();

Upvotes: 0

Related Questions