0

I currently have a try/catch around a line of code but when it errors out It's not properly printing out the error. Currently:

try { // code here } catch (\Exception $e) { return Redirect::back() ->withErrors($e->getResponse()->getBody()->getContents()["message"]); } 

prints:

{

Now if I use:

return Redirect::back()->withErrors($e->getResponse()->getBody()->getContents()); 

then I get:

{ "message":user doesn't exist }

How can I change this to, upon error, only print "user doesn't exist"?

3
  • What is var_dump($e->getResponse()->getBody()->getContents()); giving you? Commented Feb 21, 2019 at 16:47
  • """ {\n "message": "User doesn't exist."\n }\n """ Commented Feb 21, 2019 at 16:51
  • That's a json string. To get the message, you need to decode the string using json_decode() Commented Feb 21, 2019 at 16:52

2 Answers 2

3

You need to decode the json string so you can access the message attribute.

try { //code here } catch (\Exception $e) { $response = json_decode($e->getResponse()->getBody()->getContents()); $message = $response->message; return Redirect::back()->withErrors($message); } 
Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to access a serialized JSON string with array access. This will obviously fail. Here a 1:1 solution which includes the JSON decoding.

try { // code here } catch (\Exception $e) { return (json_decode(Redirect::back() ->withErrors($e->getResponse()->getBody()->getContents()))->message; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.