Php exceptions

1,553 views

Published on

PHP Exceptions tips
How to use exceptions properly?

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,553
On SlideShare
0
From Embeds
0
Number of Embeds
618
Actions
Shares
0
Downloads
28
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Php exceptions

  1. 1. PHP Exceptions tipsHow to use exceptions properly? Damian Sromek damiansromek.pl 2012-05
  2. 2. Whats an exception?Software can not finish task by performingregular scenario and you should not ignore it.● External system does not work eg. database, network, filesystem● Software is used/configured wrong eg. credentials not set● Theres a bug in software eg. somehow program came to invalid state, object was requested to do something inappropriate / "stupid"
  3. 3. Whats NOT an exception?Software can not finish a task but you know itsnothing strange when some criteria are notmet.● Validator failure eg. wrong form field value, wrong credentials when logging inDatabase access methods● findByPK - should return "null" if no unique result● findAll - should return empty collection if no results
  4. 4. Main types of exceptions● LogicException Software got to wrong state but it will not happen again when programmer fixes the code eg. filling missing configuration, better form validation● RuntimeException Software got to wrong state because of external dependency that could not have been avoided any way eg. network error, database failure
  5. 5. PHP spl exceptionshttp://php.net/manual/en/language.exceptions.phphttp://www.php.net/manual/en/spl.exceptions.phpSadly theres not much about exceptions in PHP documentation.http://www.php.net/~helly/php/ext/spl/classException.htmlException LogicException BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException OutOfRangeException RuntimeException OutOfBoundsException OverflowException RangeException UnderflowException UnexpectedValueException
  6. 6. Exceptions instead of PHP errorsConvert PHP errors to exception to get bettercontrol over your softwarehttp://www.php.net/manual/en/class.errorexception.php<?phpfunction exception_error_handler ($errno, $errstr, $errfile , $errline ) { throw new ErrorException ($errstr, 0, $errno, $errfile , $errline );}set_error_handler ("exception_error_handler" );
  7. 7. Problems with exceptions● Some use them to control the flow of application● Sometimes its hard to distinguish which exception class to use● Topic is not as much highlighted as it should be :(
  8. 8. Benefits (when used properly)● Software is much more predictable and user friendly when there are some problems with external system (WebService) etc.● Its much easier to find out what failed● Its much easier to find the bug
  9. 9. Main advantages over error flags(booleans, integers etc.)● Much less "if" statements which results in more maintainable code● You can explain why software fails by sending descriptive message and stack trace
  10. 10. Ideal exception● Tells you what happened, why it happened and (if possible) how to fix it.● Is ideal log message● Is not thrown ;) Handle error in place where it happened if you can.Eg.● new RuntimeException("Could not contact web service [url = $webServiceUrl, httpCode = $httpCode] to log user in [user id = $userId].");● throw new Canaldigital_PaymentService_Exception(Could not store customer product . "[Customer.id = {$customer->id}; Product.id = {$product->id}].");● throw new Exception("Auth server error"); // NOT!
  11. 11. Layer/library exceptions● Use spl exceptions as much as possible● Use "marker interface" to group exceptions thrown by library etc. eg. like in Symfony2, Zend Framework 2namespace MyApi;interface Exception {};class RuntimeException extends RuntimeException {};// so you can handle specific module/layer exceptionstry {...} catch (MyApiRuntimeException $myApiRuntimeEx) {...} catch (MyApiException $myApiEx) {..} catch (RuntimeException $runtimeEx) {...}
  12. 12. Do NOT!● empty try-catch If you dont know what to do with exception/error just let it go up! At the point when context let you decide what to do now you can handle it in the right way.
  13. 13. PHPDoc@throws DbException on DB erroror even better@throws MethodNotAllowedHttpException //self describing
  14. 14. Testing exceptions● @expectedException InvalidArgumentException● @expectedExceptionMessage Right Message (@see assertContains)● @expectedExceptionCode 20● http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit. html#writing-tests-for-phpunit.exceptions
  15. 15. Appendix A - Exceptions in PHP docclass LogicException extends ExceptionException that represents error in the program logic.This kind of exceptions should directly leed to a fix in your code- Exception that represents error in the program logic. This kind of exceptions should directly lead to a fix in your code.class BadFunctionCallException extends LogicExceptionException thrown when a function call was illegal.- Exception thrown if a callback refers to an undefined function or if some arguments are missing.class BadMethodCallException extends BadFunctionCallExceptionException thrown when a method call was illegal- Exception thrown if a callback refers to an undefined method or if some arguments are missing.class DomainException extends LogicExceptionException that denotes a value not in the valid domain was used.This kind of exception should be used to inform about domain erors in mathematical sense.- Exception thrown if a value does not adhere to a defined valid data domain.class InvalidArgumentException extends LogicExceptionException that denotes invalid arguments were passed.- Exception thrown if an argument does not match with the expected value.
  16. 16. Appendix A - Exceptions in PHP docclass LengthException extends LogicExceptionException thrown when a parameter exceeds the allowed length.This can be used for strings length, array size, file size, number of elements read from an Iterator and so on.- Exception thrown if a length is invalid.class OutOfRangeException extends LogicExceptionException thrown when an illegal index was requested.This represents errors that should be detected at compile time.- Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.class RuntimeException extends ExceptionException thrown for errors that are only detectable at runtime.class OutOfBoundsException extends RuntimeExceptionException thrown when an illegal index was requested.This represents errors that cannot be detected at compile time.- Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.class OverflowException extends RuntimeExceptionException thrown to indicate arithmetic/buffer overflow.- Exception thrown when adding an element to a full container.
  17. 17. Appendix A - Exceptions in PHP docclass RangeException extends RuntimeExceptionException thrown to indicate range errors during program execution.Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.- Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version ofDomainException.class UnderflowException extends RuntimeExceptionException thrown to indicate arithmetic/buffer underflow.- Exception thrown when performing an invalid operation on an empty container, such as removing an element.UnexpectedValueException extends RuntimeException- Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain typeor value not including arithmetic or buffer related errors.
  18. 18. Thank you :)

×