CakePHP : Monolog package throw runtime exception and application stop working - php

composer.json packages as below,
"monolog/monolog": "~1.25.4",
"newrelic/monolog-enricher": "^1.0",
Below file is throwing run time exception,
vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php
<?php
namespace Monolog\Handler\Curl;
class Util
{
private static $retriableErrorCodes = array(
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND,
CURLE_READ_ERROR,
CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR,
);
/**
* Executes a CURL request with optional retries and exception on failure
*
* #param resource $ch curl handler
* #throws \RuntimeException
*/
public static function execute($ch, $retries = 5, $closeAfterDone = true)
{
while ($retries--) {
if (curl_exec($ch) === false) {
$curlErrno = curl_errno($ch);
if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) {
$curlError = curl_error($ch);
if ($closeAfterDone) {
curl_close($ch);
}
throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
}
continue;
}
if ($closeAfterDone) {
curl_close($ch);
}
break;
}
}
}
if a runtime error occurs, we don't want to stop application execution to add a log.
How can I handle such a situation?
I tried to overwrite class vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php
add the below code in the composer.json file
"autoload": {
"psr-4": {
"Monolog\\Handler\\Curl\\" : "lib/MonologCurl",
}
}
created the same Util.php class in lib/MonologCurl directory to use modified code
and run composer dump-autoload
it is throwing an error as below
Fatal error: Uncaught Error: Class 'Monolog\Handler\Curl\Util' not found in /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/Handler.php:138 Stack trace: #0 /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/api1/Handler.php(53): NewRelic\Monolog\Enricher\AbstractHandler->sendBatch('[{"message":"St...') #1 /test/instances/fd/local/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php(92): NewRelic\Monolog\Enricher\Handler->handleBatch(Array) #2 /test/instances/fd/local/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php(108): Monolog\Handler\BufferHandler->flush() #3 [internal function]: Monolog\Handler\BufferHandler->close() #4 {main} thrown in /test/instances/fd/local/vendor/newrelic/monolog-enricher/src/Handler.php on line 138
what should be best solution?

Related

Slim4 register_shutdown_function method not sending response

After trying various versions of my methods, I'm not getting any closer to fixing.
In the following code I just check for a time out and call the next method accordingly.
It does show all the echo'ed lines all the way to the end, except for sending the $response contents in the end. Not when sending a simple write(), not with a JSON object, nothing.
Who can help me out of my misery?
The code:
declare(strict_types=1);
namespace App\Controllers;
use App\Models\Test;
use DI\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Routing\RouteContext;
class TestController
{
public function testTimeOut(Request $request, Response $response): Response
{
// ini_set('display_errors', 0);
// Set a time limit for this method
set_time_limit(1);
// Register the shutdown function
register_shutdown_function([$this, 'shutdownCleanup'], $request, $response);
// Wait for 2 seconds (which should cause a timeout)
sleep(2);
// If the script reaches this point, the operation completed successfully
$result = __CLASS__ . " did not time out: ";
$this->container->get('flash')->addMessage('info', $result);
// Redirect to the "manage-files" route
$routeParser = RouteContext::fromRequest($request)->getRouteParser();
$url = $routeParser->urlFor('manage-files');
return $response
->withHeader('Location', $url)
->withStatus(302);
}
private function shutdownCleanup(Request $request, Response $response)
{
$last = error_get_last();
if ($last['type'] === 1) {
// A timeout occurred
$result = "A time-out occurred. You can continue using the link next to your file.";
// Flash message
$this->container->get('flash')->addMessage('danger', $result);
// Redirect to the "manage-files" route
$routeParser = RouteContext::fromRequest($request)->getRouteParser();
$url = $routeParser->urlFor('manage-files');
echo $result . $url;
// Send the response
$response = new Response();
$response = $response->withHeader('Location', $url)->withStatus(302);
return $response;
}
}
}
The complete error on this snippet of code is:
Fatal error: Maximum execution time of 1 second exceeded in
C:***slim\app\Controllers\TestController.php on line 111 A time-out
occurred. You can continue using the link next to your
file./***slim/dash/manage-files Fatal error: Uncaught Error: Cannot
instantiate interface Psr\Http\Message\ResponseInterface in
C:***slim\app\Controllers\TestController.php:142 Stack trace: #0
[internal function]:
App\Controllers\TestController->shutdownCleanup(Object(Slim\Http\ServerRequest),
Object(Slim\Http\Response)) #1 {main} thrown in
C:***slim\app\Controllers\TestController.php on line 142

Lumen 5.6 Error handling (throws exception twice)

This is my code to handle any error:
App\Exceptions\Handler::class
public function render($request, Exception $e)
{
$fe = \Symfony\Component\Debug\Exception\FlattenException::create($e);
$statusCode = $fe->getStatusCode();
$code = $fe->getCode();
$message = $fe->getMessage();
$errorObj = new \App\LOHDomain\Entities\Error($code, $message);
return response()->json(['data' => null, 'error' => $errorObj], $statusCode);
}
when I parse a fake WSDL URL to the SoapClient it throws two exceptions
{"data":null,"error":{"code":"0","message":"SOAP-ERROR: Parsing WSDL: Couldn't load from 'asdsd' : failed to load external entity \"asdsd\"\n"}}
{"data":null,"error":{"code":"1","message":"SOAP-ERROR: Parsing WSDL: Couldn't load from 'asdsd' : failed to load external entity \"asdsd\"\n"}}
So the json response became invalid
When commenting these line of codes in the vendor, it throws one exception:
Laravel\Lumen\Concerns\RegistersExceptionHandlers trait
protected function registerErrorHandling()
{
error_reporting(-1);
set_error_handler(function ($level, $message, $file = '', $line = 0) {
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
});
set_exception_handler(function ($e) {
$this->handleUncaughtException($e);
});
// register_shutdown_function(function () {
// $this->handleShutdown();
// });
}
So, What is the problem? and how to solve it without editing in the vendor?
The solution is to clear the last error, because it fired twice.
The error exception.
The second is the shutdown function.
So, the solution is:
App\Exceptions\Handler::class
public function render($request, Exception $e)
{
$fe = \Symfony\Component\Debug\Exception\FlattenException::create($e);
$statusCode = $fe->getStatusCode();
$code = $fe->getCode();
$message = $fe->getMessage();
$errorObj = new \App\Domain\Entities\ResponseEntites\Error($code, $message);
/**
* This line of code resolves the issue
*
* To reproduce the issue :
* 1) Comment this following line of code
* 2) Provide a fake WSDL URL to the SoapClient
*
* Recommendation: Remove this line if you aren't using the SoapClient
*/
error_clear_last();
return new \Illuminate\Http\JsonResponse(['data' => null, 'error' => $errorObj], $statusCode);
}
This isn't the best solution (but this is the best solution, that I tried in my case).
If you have a better tested solution please share it.
links:
Fatal exceptions are handled twice
Code change

PHP Exceptions CodeIgniter

my code is generating ssse following error:
Fatal error: Uncaught TypeError: Argument 1 passed to
CI_Exceptions::show_exception() must be an instance of Exception,
instance of Error given, called in
C:\xampp\htdocs\gog\lib\core\Common.php on line 662 and defined in
C:\xampp\htdocs\gog\lib\core\Exceptions.php:190 Stack trace: #0
C:\xampp\htdocs\gog\lib\core\Common.php(662):
CI_Exceptions->show_exception(Object(Error)) #1 [internal function]:
_exception_handler(Object(Error)) #2 {main} thrown in C:\xampp\htdocs\gog\lib\core\Exceptions.php on line 190
The line of the codes described is these:
function _exception_handler(Throwable $exception)
{
$_error =& load_class('Exceptions', 'core');
$_error->log_exception('error', 'Exception: '.$exception->getMessage(), $exception->getFile(), $exception->getLine());
// Should we display the error?
if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors')))
{
$_error->show_exception($exception); //line 662
}
exit(1); // EXIT_ERROR
}
public function show_exception(Exception $exception) //line 190
{
$templates_path = config_item('error_views_path');
if (empty($templates_path))
{
$templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
}
$message = $exception->getMessage();
if (empty($message))
{
$message = '(null)';
}
if (is_cli())
{
$templates_path .= 'cli'.DIRECTORY_SEPARATOR;
}
else
{
set_status_header(500);
$templates_path .= 'html'.DIRECTORY_SEPARATOR;
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include($templates_path.'error_exception.php');
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
}
Someone can pinpoint my problem ?
No CodeIgniter version has that _exception_handler() signature. This is what happens when you modify stock framework files.
Download a fresh copy of the latest CodeIgniter and replace yours with it.
You call show_exception(Exception $exception) from within _exception_handler(Throwable $exception). Since the former takes an Exception as argument, you cannot give it a Throwable, as you do in line 662. Exception implements the Throwable interface, but that does not guarantee all Throwables to be Exceptions (e. g. they could be of type Error).
Replace _exception_handler(Throwable $exception) with _exception_handler(Exception $exception), or change show_exception(Exception $exception) to show_exception(Throwable $exception), and change the method bodies accordingly if needed.

(400) Bad Requestwhen using the permission to the library google-api-php-client

Uploading a file and immediately do permission->update:
public function sharingFile() {
$fileId = $this->file['id'];
$permissionId = $this->file['userPermission']['id'];
try {
$permission = $this->service->permissions->get($fileId, $permissionId);
$permission->setRole('writer');
$permission->setType('default');
print_r($permission);
return $this->service->permissions->update($fileId, $permissionId, $permission);
} catch (Exception $e) {
return "Error: " . $e;
}
return NULL;
}
and get an error:
Error: exception 'Google_ServiceException' with message 'Error calling PUT
https://www.googleapis.com/drive/v2/files/0B6xE_F1PfpXTbF9IdHgxbEJueEk/permissions/me:
(400) Bad Request' in Z:\home\site.com\www\google-api-php-client\src\io\Google_REST.php:66
Stack trace:
#0 Z:\home\site.com\www\google-api-php-client\src\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 Z:\home\site.com\www\google-api-php-client\src\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 Z:\home\site.com\www\google-api-php-client\src\contrib\Google_DriveService.php(774): Google_ServiceResource->__call('update', Array)
it may be a bug in the library?
Help, please.
Your code is trying to update permissions for the document owner and make that user a writer instead. A Drive document must have exactly one owner, so your request is invalid.

Working with Zend Soap classes and auto WSDL

Something very strange.
WSDL file generates fine. Here is source simple class
class SoapTest
{
/**
* Prapapapapapapap
* #return string Bls bls
*/
public function getList()
{
return "code";
}
}
Code for WSDL, Server, Client
if (isset($_REQUEST['wsdl'])) {
$ad = new Zend_Soap_AutoDiscover();
$ad->setClass('SoapTest');
$ad->handle();
} else if ( isset($_REQUEST['client']) ) {
$client = new Zend_Soap_Client("http://localhost/test.php");
echo $client->getList();
}
else {
$server = new Zend_Soap_Server("http://localhost/test.php?wsdl");
$server->setClass('SoapTest');
$server->handle();
}
Autogenerated WSDL have some problems with SoapServer
Uncaught exception 'Zend_Soap_Server_Exception' with message 'Invalid XML' in Z:\home\localhost\www\Zend\Soap\Server.php:694 Stack trace: #0 Z:\home\localhost\www\Zend\Soap\Server.php(817): Zend_Soap_Server->_setRequest('') #1 Z:\home\localhost\www\test.php(54): Zend_Soap_Server->handle() #2 {main} thrown in Z:\home\localhost\www\Zend\Soap\Server.php on line 694
I just don't understand why? There is no extra symbol in WSDL like space or \n, all headers are specified.
Php 5.2.12
ZF 1.10.0
all problems from eAccelerator

Categories