Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

masterpowers's avatar

How to Catch the Message in an Exception? and Return it as JSON?

Hi I got this exception

if( !$user && !$profile && !$link )
            {
                throw new \Exception('User not created');
            }

if i use the code plain in tinker i got this

>>> new \Exception('User not created');
=> Exception {#741
     #message: "User not created for account",
     #file: "/home/vagrant/Code/maxims/vendor/psy/psysh/src/Psy/ExecutionLoop/Loop.php(76) : eval()'d code",
     #line: 3,
   }

The Result is an Array with a key Message

Now i want to Access that message and cast it as error to be return in my Json Response

$errors = $validator->errors()->add(message) ; // Here i want to Inject Message from the Exception but dont know what to Call it.

            return response()->json(['success' => false, 'errors' => $errors], 400);

My Only Problem is How Can i Access that Message in the array and assign it a variable and be added to my $errors Variable

I Tried this
$error = new \Exception('user is not created')
it just return
=> Exception {#748
     #message: "user is not created",
     #file: "/home/vagrant/Code/maxims/vendor/psy/psysh/src/Psy/ExecutionLoop/Loop.php(76) : eval()'d code",
     #line: 3,
   }

but When i Need to Access the Message as such
$error->message 
it gave me
Fatal error: Cannot access protected property Exception::$message

So i Can Return it As A JSON Object

Hope someone can help me

0 likes
5 replies
masterpowers's avatar
masterpowers
OP
Best Answer
Level 5

Finally Got My Answer and Hope to Share this i tried

$error->getMessage()

It Seems that you Need to Call the getMessage() method to Access that Property

:)

1 like

Please or to participate in this conversation.