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);
}
Related
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());
}
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;
}
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;
}
I have code like this:
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = file_get_contents($nbg_xml_url);
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}`
and problem is that, when file_get_contents can not read url (may be site not responding or something like this..) my code writes error: failed to open stream: HTTP request failed! and execution goes direct to finally block bypass catch block without entering in it..
any ideas?
You can set an empty error handler to prevent the warning and afterward throw a custom exception in case of failure. In this case I would write a custom file_get_content like so:
function get_file_contents($url) {
$xml_content = file_get_contents($url);
if(!$xml_content) {
throw new Exception('file_get_contents failed');
}
return $xml_content;
}
and would use it in your block:
set_error_handler(function() { /* ignore errors */ });
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = get_file_contents($nbg_xml_url); //<----------
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}
Then remember to restore the error handler calling:
restore_error_handler();
Note that when using your own error handler it will bypass the
error_reporting
setting and all errors included notices, warnings, etc., will be passed to it.
$xml_content = file_get_contents($nbg_xml_url);
The function file_get_contents does not throw an exception. Thus an exception will not be thrown if as you say the file is not found.
From the docs:
An E_WARNING level error is generated if filename cannot be found...
This function returns the read data or FALSE on failure. So you could check if $xml_content is FALSE ($xml_content === false) and proceed accordingly.
This is a php code for catching any error or exception.
Throwable is the base interface for any object that can be thrown via a throw statement, including Error and Exception.
This will catch fatal errors too. Without throwable it will not catch fatal errors.
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}
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)