0

On laravel site in controller I catch custom KeyIsNotProvidedException Exception:

<?php
        try {
            $data = $this->method();
            ...
        } catch (KeyIsNotProvidedException $e) {

            return response()->json([
                'code' => 500,
                'message' => 'Check if valid Key is Provided',
            ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
        } catch (\Error | \Exception $e) {

            return response()->json([
                'error_message' => $e->getMessage(),
            ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
        }

Also Making test for this controller when custom error is raised I wonder which class have I to use here:

...
$this->withoutExceptionHandling();
$this->expectException(WhichClassMustBeUsedHere::class); // ???
...

$this
    ->post(route('items.action'), [
    ]);

Also as in the controller I return 500 code, which best practice can be used here for controller and for test?

   "laravel/framework": "^10.8",
   "phpunit/phpunit": "^10.1",

Thanks in advance!

Petro Gromovo
  • 1,755
  • 5
  • 33
  • 91

1 Answers1

1

To expect the Exception:

$this->expectException(KeyIsNotProvidedException::class)

To assert against the 500 status

$this->post(route('items.action'), [])->assertServerError();
Rory
  • 2,175
  • 1
  • 27
  • 37
  • As I catch KeyIsNotProvidedException in my controller, but it is not returned from controller action, do I need to use in expectException other class? Which ? Looks like $response->assertServerError() works ok, but can I conbine it with expectException method ? – Petro Gromovo Aug 06 '23 at 07:37
  • 1
    `$this->withoutExceptionhandling()` sets up a new default exception handler. Therefore it will only respond to uncaught exceptions. If your plan is to manually emit a 500 server error I would just use `assertServerError()` and not worry about the exception – Rory Aug 06 '23 at 09:01