properly handle error message in laravel controller - php

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"?

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);
}

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;
}

Related

Official API client library for PHP (mailchimp-marketing-php) error detail truncated [duplicate]

Guzzle http is truncating exceptions with more than 120 characters, but I need to log the full exception message. How can I do this?
I am using laravel 4.2.22.
try {
// whatever
} catch (\GuzzleHttp\Exception\RequestException $ex) {
return $ex->getResponse()->getBody()->getContents();
// you can even json_decode the response like json_decode($ex->getResponse()->getBody()->getContents(), true)
}
It is the same for Laravel 5 and 4
try {
$response = $client->post($path, $params);
} catch (\GuzzleHttp\Exception\RequestException $ex) {
\Log::debug('error');
\Log::debug((string) $ex->getResponse()->getBody());
throw $ex;
}
if you just go to $ex->getMessage(), you will get
(truncated...)
at the end.
Might be better solution:
try {
// do request here like:
// return $client->post($path, $params);
} catch (\GuzzleHttp\Exception\ServerException $ex) {
$exFactoryWithFullBody = new class('', $ex->getRequest()) extends \GuzzleHttp\Exception\RequestException {
public static function getResponseBodySummary(ResponseInterface $response)
{
return $response->getBody()->getContents();
}
};
throw $exFactoryWithFullBody->create($ex->getRequest(), $ex->getResponse());
}

How to catch SQL Exception in Laravel 5

Hay I'm creating a code like this :
\Log::info("saving log....");
try{
$data = AstronautCandidateLog::insert($request->logs);
}catch (SQLException $e)
{
\Log::info("SQL Exception happened");
}catch (Exception $e)
{
\Log::info("Exception happened");
}
\Log::info("status save data : ". $data);
But it seems that my Exception never get hit. So how to capture exception in laravel when something wrong in sql query...??
Thanks in advance.
Try this
try {
//Your code
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
}
OR
use Illuminate\Database\QueryException;
try {
//Your code
} catch(QueryException $ex){
dd($ex->getMessage());
}
My case: add \ before Exception class otherwise it not handle
try
{
//write your codes here
}
catch(\Exception $e) {
Log::error($e->getMessage());
}
Make sure to use the Exception library in your controller. From there you can do:
try{
Some queries . . .
}catch(Exception $e){
return response()->json([
'error' => 'Cannot excecute query',
],422);
}
To implement an exception in Laravel, simply include the Exception class, at the top of your controller as
Use Exception;
Then wrap the lines of code you wish to catch an exception on using try-catch statements
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
You can also return your errors in json format, incase you are making an Ajax request, this time, remember to include the Response class at the top of your controller
Use Response;
Use Exception;
then wrap your codes in a try-catch statement as follows
try
{
//write your codes here
}
catch(Exception $e)
{
return response()->json(array('message' =>$e->getMessage()));
}
I hope this will solve your problem, you can learn more on Laravel and Error handeling here

How do I catch more than one exception type?

I have the following code -
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
}
return [];
}
I added this b/c when the page 404s I get the ClientException, however if the server returns a 500 error I get a ServerException - I tried just replacing this with catch(Exception $ex), but I still get the unhandled/uncaught exception error.
You can have multiple catch blocks for different exception types in php:
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch(\GuzzleHttp\Exception\ServerException $e) {
//handle it...
}
However, the assuming the Guzzle exceptions extend the general php Exception class (which of course they do), changing it to just Exception $e should work. Are you sure this is where the exception is being thrown?
On the guzzle site http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions you can see GuzzleHttp\Exception\TransferException base for all the client/server extensions, so you could just try to catch a GuzzleHttp\Exception\TransferException;
just list multiple catches:
try {
...
} catch (FooException e) {
...
} catch (BarException e) {
...
} catch (Exception e) {
...
}
Just keep catching
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch (ServerException) {
//some code
}
return [];
}
be aware of namespaces, if you try to catch Exception it will catch all exceptions, if it did not, maybe you didnt include the exception as use Exception or tried to catch \Exception
The catch can be chained one after the other for handling multiple Error Types.
public function getPosts($limit = 25, $author = null) {
try {
} catch(\GuzzleHttp\Exception\ClientException $e) {
return [];
} catch(\GuzzleHttp\Exception\ServerException $e) {
return [];
}
return [];
}

PHP exception inside catch: how to handle it?

Suppose to have a PHP code inside a try...catch block. Suppose that inside catch you would like to do something (i.e. sending email) that could potentially fail and throw a new exception.
try {
// something bad happens
throw new Exception('Exception 1');
}
catch(Exception $e) {
// something bad happens also here
throw new Exception('Exception 2');
}
What is the correct (best) way to handle exceptions inside catch block?
Based on this answer, it seems to be perfectly valid to nest try/catch blocks, like this:
try {
// Dangerous operation
} catch (Exception $e) {
try {
// Send notification email of failure
} catch (Exception $e) {
// Ouch, email failed too
}
}
You should not throw anything in catch. If you do so, than you can omit this inner layer of try-catch and catch exception in outer layer of try-catch and process that exception there.
for example:
try {
function(){
try {
function(){
try {
function (){}
} catch {
throw new Exception("newInner");
}
}
} catch {
throw new Exception("new");
}
}
} catch (Exception $e) {
echo $e;
}
can be replaced to
try {
function(){
function(){
function (){
throw new Exception("newInner");
}
}
}
} catch (Exception $e) {
echo $e;
}
You have 2 possible ways:
You exit the program (if it is severe) and you write it to a log file and inform the user.
If the error is specifically from your current class/function,
you throw another error, inside the catch block.
You can use finally. Code in this branch will be executed even if exception is thrown within catch branch

How to set a HTTP_Exception_404

I am using kohana 3.2 and kohana-error module is working fine, when the page does not exist.
But I have this situation: the page exist, but no data is coming, because the data does not exist. I am using the route param to check de database.
So I did this,
if($response )
{
return $response;
} else {
throw new HTTP_Exception_404('Page Not Found');
}
If there are data return, if not, create a ‘Page Not Found’ and I supose it will be caught by the kohana-error module but it is not....
Is that possible? Is this the right approach?
In your index.php, you do the following:
$request = Request::factory();
try
{
$response = $request->execute();
if (!$response->body())
{
throw new HTTP_Exception_404();
}
}
catch (Exception $exc)
{
if ($exc instanceof HTTP_Exception_404)
{
$response = Request::factory('your/404error/controller')->execute();
}
else
{
// rethrow exception
throw $exc;
}
}
echo
$response
->send_headers()
->body();
That way, you can execute a controller for each HTTP exception, or you can use a catch all 404 page for all exceptions (50x and 40x errors)

Categories