How to catch ReflectionException in Laravel 5? - php

$module - is one of my classes, based on Interface and must be have public function getController. I can forget to add getController function in class, and after run i have this error:
ReflectionException in Container.php line 776:
Class App\Http\Controllers\ does not exist
and want to catch this exception, but this code not work:
try
{
\Route::get($module->getUrl(), $module->getController() . '#index');
}
catch (\ReflectionException $e)
{
echo 123123;
}
Code example:
namespace App\MyModules;
MyModuleManager::bindRoute();
interface MyModuleInterface
{
public function getUrl();
public function getController();
}
class MyClass implements MyModuleInterface
{
public function getUrl()
{
return '/url';
}
/*
* for example: this method i forgdet to add
* and in ModuleManager::bindRoute i want to cath exception
*
public function getController()
{
}
*/
}
class MyModuleManager
{
static public function bindRoute()
{
$module = new MyClass();
try
{
\Route::get($module->getUrl(), $module->getController() . '#index');
}
catch (\ReflectionException $e)
{
echo 123123;
}
}
}

In L5 you can handle this exception globally:
// Exceptions/Handler.php
use ReflectionException;
public function render($request, \Exception $e)
{
if ($e instanceof ReflectionException) {
// …
}
return parent::render($request, $e);
}

Related

Call to undefined method App\Helpers Laravel

I want to call function payrollProcess from another class inside my controller.
here's my code :
public function save(Request $request, $obj = null)
{
PayrollHelper::payrollProcess($PayrollPeriod);
return view('payroll_process.form');
}
and this is payrollHelper class code :
<?php
namespace App\Helpers;
use App\Helpers\Exceptions\ValidationException;
use App\Models\Config;
use App\Models\Driver;
use App\Models\DriverPayable;
use App\Models\PayrollPeriod;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
final class PayrollHelper {
public static function processPayroll(PayrollPeriod $payrollPeriod)
{
try {
$drivers = Driver::where('active', true)->get();
foreach ($drivers as $driver) {
$payable = $payrollPeriod->driverPayables()
->where('driver_id', $driver->id)->first();
if (!$payable) {
$payable = new DriverPayable;
}
$payable->payrollPeriod()->associate($payrollPeriod);
$payable->driver()->associate($driver);
if (!$payable->save()) {
\Log::info($payable->errors());
throw new ValidationException($payable->errors());
}
}
} catch (Exception $e) {
Log::error($e);
SessionHelper::setMessage(
'Unable to process payroll, Please contact system Administrator'
);
} catch (ValidationException $e) {
Log::info($e->errors);
SessionHelper::setMessage($e->errors);
}
}
}
?>
I got this error when i run it. Call to undefined method App\Helpers\PayrollHelper::payrollProcess()
any idea ?
In PayrollHelper class you have defined processPayroll method so in your controller
public function save(Request $request, $obj = null)
{
PayrollHelper::payrollProcess($PayrollPeriod);
return view('payroll_process.form');
}
you are accessing undefined method

PHP: add a custom method to a(n internal) class (derived from exception class) at runtime

I extended the exception class amongst other things to add a method getMessageHTML().
In my application I want to catch any exception - also exceptions of derived internal classes like e.g. the ReflectionException - and want to be able to use a getMessageHTML() method or other custom methods on any exception and any derived exception.
Is there any way, to add a method or trait to an internal class like the exception class or the ReflectionException class at runtime?
The only solution that comes to my mind is to wrap any catched exception into my extended exception class like:
$anyException = new Exception(); //or ReflectionException, or ...
$wrappedException = MyException::wrap($anyException);
$wrappedException->getMessageHTML(); //or any other custom method
is there any implementation, that allows to introduce a method to every derived internal or foreign class/object, so that any object knows it?
$anyException = new Exception(); //or ReflectionException, or ...
$anyException->getMessageHTML();
then i could simply do:
try
{
throw <anyException>(); //like throw Exception() or throw ReflectionException() ...
}
catch($e)
{
$e->getMessageHTML(); //its assured that the method is known.
}
For now I am doing it like this:
class MyException extends Exception
{
protected static function cast($destination, $sourceObject)
{
if(is_string($destination))
$destination = new $destination();
$sourceReflection = new \ReflectionObject($sourceObject);
$destinationReflection = new \ReflectionObject($destination);
$sourceProperties = $sourceReflection->getProperties();
foreach($sourceProperties as $sourceProperty)
{
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name))
{
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
}
else
$destination->$name = $value;
}
return $destination;
}
public static function wrap(Exception $exception)
{
$wrap = $exception;
if(!$exception instanceof MyException)
$wrap = self::cast(__CLASS__, $exception);
return $wrap;
}
public function getMessageHTML()
{
//some code ...
}
}
try
{
throw new ReflectionException('test');
}
catch(Exception $e)
{
$e = MyException::wrap($e);
echo $e->getMessageHTML();
}
or - simpler - and with the advantage to have the previous exception available:
class MyException extends Exception
{
public static function wrap(Exception $exception)
{
$wrap = $exception;
if(!$exception instanceof AppException)
{
try
{
throw new AppException($exception->getMessage(), $exception->getCode(), $exception);
}
catch(AppException $e)
{
$wrap = $e;
}
}
return $wrap;
}
public function getMessageHTML()
{
//some code ...
}
}

Codeigniter extended core exception class function issue

I have extend codeigniter native library (exceptions) and define a new function.
Here is code
class MY_Exceptions extends CI_Exceptions {
public function __construct() {
parent::__construct();
}
public function show_error($heading, $message, $template = 'error_general', $status_code = 500) {
try {
} catch (Exception $e) {
}
}
public function custom_errors($id, $message) {
try {
//some code here
} catch (Exception $e) {
}
}
}
I put this above class in application/core/My_Exceptions.php for autoload as mention in documentation. https://www.codeigniter.com/user_guide/general/core_classes.html
The problem is, i can't access function custom_errors($id, $message) in controller while show_error() is available in the same controller
I try like this
$this->my_exceptions->custom_errors($id, $message)
And
$this->exceptions->custom_errors($id, $message)
But get this error "Call to a member function custom_errors() on a non-object"
If codeigniter autoload it than it should be available here.
Please help me what i am doing wrong?

php manual exception example

So I was reading the php manual on Extending Exceptions and read the example code. My question about the following code is: why does var_dump($o) evaluate to null? Is it because the constructor of the class TestException throws an exception, hence not allowing the completion of the object? I am almost certain that is the reason.
Nevertheless here is the code for examination:
<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0, Exception $previous = null) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code, $previous);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
/**
* Create a class to test the exception
*/
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 is not allowed as a parameter', 6);
break;
default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}
// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
?>
Have a look at PHP exception from PHP official site.
Example:
<?php
class MyException extends Exception { }
class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
/* rethrow it */
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>

Exception handling in php

I have this scenario:
Interface ClassInterface
{
public function getContext();
}
Class A implements ClassInterface
{
public function getContext()
{
return 'CONTEXTA';
}
//Called in controller class
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class B implements ClassInterface
{
public function getContext()
{
return 'CONTEXTB';
}
//Called in controller class
public function Bmethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class Helper {
public function helperMethod(ClassInterface $interface)
{
try {
$this->verifyContext($interface->getContext());
//dosomething
} catch(\Exception $ex) {
throw $ex;
}
}
private function verifyContext($context) {
if (condition1) {
throw new \UnexpectedValueException('Invalid context.');
}
return true;
}
}
I want my controller class which calls Amethod1 and Bmethod1 to know the type of exception(s) thrown in the process. Is it advisable to rethrow an exception just like it was presented?
Do you think the throw-catch-throw-catch-throw structure reasonable in this case?
Yes, totally reasonable. But: your specific example can be simplified from:
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
To:
public function Amethod1()
{
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
}

Categories