Kit-PHPEncoder icon indicating copy to clipboard operation
Kit-PHPEncoder copied to clipboard

All exceptions should inherit from a base PHPEncoder\Exception

Open jmwebservices opened this issue 7 years ago • 2 comments

Thanks for this project. I have been using it for several months to prettify a configuration array that is modified by a UI and written to a file.

It would be nice if all exceptions thrown by PHPEncoder would inherit from a base PHPEncoder\Exception class. Currently, InvalidOptionException is the only PHPEncoder specific exception while InvalidArgumentException and RuntimeException are thrown directly. Implementing this recommendation will make it possible to distinguish between PHPEncoder exceptions and other exceptions thrown by an app using PHPEncoder (see example below).

public function write( $content ) : bool
{

	try
	{

		if( !$this->validate( $content ) )
			throw new APP_Exception( 'SOME USEFUL MESSAGE.' );

		$put = ( new \Riimu\Kit\PHPEncoder\PHPEncoder )->encode( $content );

		if( file_put_contents( $this->path(), $put ) === false )
			throw new APP_Exception( 'SOME USEFUL MESSAGE.' );

	}
	catch( APP_Exception $e )
	{
		// do something with APP thrown exception
	}
	catch( \Riimu\Kit\PHPEncoder\Exception $e )
	{
		// do something with PHPEncoder thrown exception
	}

	return true;
}

jmwebservices avatar Oct 08 '18 22:10 jmwebservices

Not an unreasonable request. I always struggle with how to properly organize and categorize exceptions in libraries. Now that I look closely into this project, it seems I'm already a bit inconsistent with the existing exceptions.

I'll keep this in mind for future improvements, but I won't promise an immediate fix as proper organization requires a bit of a BC break.

Riimu avatar Oct 10 '18 10:10 Riimu

@Riimu Thanks for responding! It's very discouraging when one submits issues or PRs to a repo and the owner ignores it completely!

As for implementing this in a BC way, you could do something like the following:

namespace Riimu\Kit\PHPEncoder;

interface Exception{}

class InvalidOptionException extends \InvalidArgumentException implements Exception{}
class RuntimeException extends \RuntimeException implements Exception{}
class InvalidArgumentException extends \InvalidArgumentException implements Exception{}

This configuration will allow us to catch \RuntimeException and \InvalidArgumentException exceptions (for BC purposes) and also \Riimu\Kit\PHPEncoder\Exception exceptions.

I am pretty sure empty interfaces are frowned upon, but it looks like a good fit.

jmwebservices avatar Oct 10 '18 18:10 jmwebservices