0

I have created a custom policy for a model and the policy logic works really well with a GraphQL mutation. I'm just wondering can I somehow pass my custom error message as a GraphQL response?

This is an example of a policy class:

use App\Models\MyModel;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class MyModelPolicy
{
    use HandlesAuthorization;
    
    public function update(User $user, MyModel $my_object)
    {
        if (!$my_object->checkSomething()) {
            // Throws an exception
            $this->deny('My custom error message should be delivered to the GraphQL client..');
        }
        
        return true;
    }
}

But the message in the exception gets discarded:

2 Answers2

0

You can use try catch to throw your custom response though I personally never use try catch block in model(only in controllers)

public function update(User $user, MyModel $my_object)
    try {
        if (!$my_object->checkSomething()) {
            // Throws an exception
            throw new \Exception('YourCustomException');
            $this->deny('My custom error message should be delivered to the GraphQL client..');
        }
        
        return true;
    }catch (\Exception $e) {
            if ($e->getMessage() == 'YourCustomException') {
                $data = [
                    'status' => 'error',
                    'message' => 'YourCustomException is not authorized.',
                ];
                return response($data, 200);
            }
     }

You can change your status code and message accordingly. Here response() is HTTP response object.

bhucho
  • 3,903
  • 3
  • 16
  • 34
  • It is not recommended to use status codes other than 200 for GraphQL responses that entered execution. – spawnia Aug 18 '20 at 15:15
0

Consider https://lighthouse-php.com/master/digging-deeper/error-handling.html#user-friendly-errors.

webonyx/graphql-php offers the GraphQL\Error\ClientAware interface, that can be implemented by Exceptions to control how they are rendered to the client.

By default, given you turned off debug mode, exception messages are not shown to the client.

Since you don't control the thrown message directly when using $this->deny(), you could register an error handler within Lighthouse to recognize the thrown AuthorizationException and convert it to a ClientAware exception.

https://lighthouse-php.com/master/digging-deeper/error-handling.html#registering-error-handlers

spawnia
  • 879
  • 6
  • 13