How to set a HTTP_Exception_404 - php

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)

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

PHP throws an exception in subroutine stops working

I have a custom class with function, which calls a function of the Yii2 core BasisAuthentication. In the core module is defined, if the credentials are not valid,
throw new UnauthorizedHttpException('Your request was made with invalid credentials.');
With this, the whole request is ended. But I need to go further (because it is a REST request).
I've tried to prevent from that with
try {
$identity = $basic_Auth->authenticate($user, $request, null );
} catch (Exception $e) {
return null;
}
But this is not working. I don't want to adapt the core files of Yii. What can I do?
try {
$identity = $basic_Auth->authenticate($user, $request, null );
} catch (\Throwable $e) {
return null;
}

Laravel: The abort() helper ignored in the catch block

I'm trying to throw a 404 page if a file that's supposed to be downloaded doesn't exist:
try {
$fileContents = file_get_contents($url);
if ($fileContents === false) {
abort(404);
}
} catch (\Exception $e) {
abort(404);
}
Thing is, that if the file under the specified $url is missing, an exception is thrown and the execution lands in the catch block - which is fine. However, the abort(404) doesn't happen at all. Instead, a blank page is served.
Why is the abort() ignored? I can put a die('foo') in the catch and it will be echoed out.
Note - the abort() helper source:
function abort($code, $message = '', array $headers = [])
{
return app()->abort($code, $message, $headers);
}
I tested this and it works as expected. Check if you have any custom 404 error page that's resulting in the blank page or if you have any custom exception handlers set.
try {
$fileContents = file_get_contents($url);
if ($fileContents === false) {
throw new \Exception;
}
} catch (\Exception $e) {
abort(404);
}

Guzzle Curl error not catche by try catch statement (Laravel)

In a Laravel project I need to call API REST to delete remote data.
My problem is that my catch statement dont catch Guzzle exception when I got an error. My code is the following :
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (Exception $e) {
var_dump($e);exit();
}
The exception is catched by Laravel but not in my catch statement. The exception throwed by Guzzle is :
GuzzleHttp\Ring\Exception\ConnectException
It raised in my line 3 of script and it doesn't catched in my script. Could you give me a way to catch the Guzzle Exception ?
I should indicate that I already seen these posts but I not get a good response :
How to resolve cURL Error (7): couldn't connect to host?
and
Catching cURL errors from Guzzle
It worked with me when I used
\GuzzleHttp\Exception\ConnectException
instead of
\Guzzle\Http\Exception\ConnectException
I had a similar problem and solved it using the following thing.I have used your example and given the inline comments for you to understand.
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
if($status == 200){
$response = $response->json();
}else{
// The server responded with some error. You can throw back your exception
// to the calling function or decide to handle it here
throw new \Exception('Failed');
}
} catch (\Guzzle\Http\Exception\ConnectException $e) {
//Catch the guzzle connection errors over here.These errors are something
// like the connection failed or some other network error
$response = json_encode((string)$e->getResponse()->getBody());
}
Hope this helps!
Maybe that exception is not extending the Exception class. You may try to catch it like:
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (\GuzzleHttp\Ring\Exception\ConnectException $e) {
var_dump($e);exit();
} catch (Exception $e) {
// ...
}
You probably mean to catch \Exception (in the root namespace), either by adding the backslash in the catch statement or a use Exception statement.
Just Updating the answer to the new Guzzle exception namespace
try {
$client = new \GuzzleHttp\Client();
$request = $client->delete(Config::get('REST_API').'/order-product/'.$id);
$status = $request->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
var_dump($e);exit();
}

Get all the exceptions from one try catch block

I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}

Categories