Slide 1

Slide 1 text

HANDLING EXCEPTIONAL CONDITIONS HANDLING EXCEPTIONAL CONDITIONS WITH GRACE AND STYLE WITH GRACE AND STYLE Nikola Poša · @nikolaposa

Slide 2

Slide 2 text

Я радий бути тут Я радий бути тут

Slide 3

Slide 3 text

Я радий бути тут Я радий бути тут ABOUT ME ABOUT ME Software Architect specializing in PHP-based applications Lead Architect at Arbor Education Partners PHP Serbia Conference co-organizer  @nikolaposa  blog.nikolaposa.in.rs

Slide 4

Slide 4 text

AGENDA AGENDA Approaches for dealing with exceptional conditions Set of applicable best practices for managing exceptions in a proper way Solution for establishing central error handling system Few tips for testing exceptions

Slide 5

Slide 5 text

HAPPY PATH HAPPY PATH a.k.a. Normal Flow Happy path is a default scenario featuring no exceptional or error conditions, and comprises nothing if everything goes as expected. Wikipedia “

Slide 6

Slide 6 text

$user = $userRepository->get('John'); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } 1 2 3 4 5

Slide 7

Slide 7 text

$user = $userRepository->get('John'); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } 1 2 3 4 5 if ($user->isSubscribedTo($notification)) { Fatal error: Call to a member function isSubscribedTo() on null $user = $userRepository->get('John'); 1 2 3 $notifier->notify($user, $notification); 4 } 5 6 7 8

Slide 8

Slide 8 text

$user = $userRepository->get('John'); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } 1 2 3 4 5 $user = $userRepository->get('John'); if (null !== $user && $user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } 1 2 3 4 5

Slide 9

Slide 9 text

Null checks ood if (null !== $user) { if (null !== $todo) { if (null !== $notification) { $user = $userRepository->get('John'); 1 2 3 $todo = $todoRepository->get('Book flights'); 4 5 6 $notification = TodoReminder::from($todo, $user); 7 8 9 if ($user->isSubscribedTo($notification)) { 10 $notifier->notify($user, $notification); 11 } 12 } 13 } 14 } 15

Slide 10

Slide 10 text

Vague Interface interface UserRepository { public function get(string $username): ?User; }

Slide 11

Slide 11 text

Vague Interface interface UserRepository { public function get(string $username): ?User; } interface UserRepository { /** * @param UserId $id * @return User|bool User instance or boolean false if User w */ public function get(string $username); }

Slide 12

Slide 12 text

DO NOT MESS WITH DO NOT MESS WITH NULL NULL

Slide 13

Slide 13 text

When we return null, we are essentially creating work for ourselves and foisting problems upon our callers. Robert C. Martin, "Clean Code" “

Slide 14

Slide 14 text

If you are tempted to return null from a method, consider throwing an exception or returning a Special Case object instead. Robert C. Martin, "Clean Code" “

Slide 15

Slide 15 text

THROW EXCEPTION THROW EXCEPTION interface UserRepository * @throws UserNotFound public function get(string $username): User; 1 { 2 /** 3 * @param string $username 4 5 * @return User 6 */ 7 8 } 9 throw new UserNotFound(); final class DbUserRepository implements UserRepository 1 { 2 public function get(string $username): User 3 { 4 $userRecord = $this->db->fetchAssoc('SELECT * FROM use 5 6 if (false === $userRecord) { 7 8 } 9 10 return User::fromArray($userRecord); 11 } 12 } 13

Slide 16

Slide 16 text

interface UserRepository { @throws UserNotFound public function get(string $username): User; }

Slide 17

Slide 17 text

try { $user = $userRepository->get($username); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } } catch (UserNotFound $ex) { $this->logger->notice('User was not found', ['username' => $u }

Slide 18

Slide 18 text

try { $user = $userRepository->get($username); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); } } catch (UserNotFound $ex) { $this->logger->notice('User was not found', ['username' => $u } try { $this->notifyUserIfSubscribed($username, $notification); } catch (\Throwable $ex) { $this->log($ex); }

Slide 19

Slide 19 text

SPECIAL CASE SPECIAL CASE a.k.a. Null Object A subclass that provides special behavior for particular cases. Martin Fowler, "Patterns of Enterprise Application Architecture" “

Slide 20

Slide 20 text

class UnknownUser extends User { public function username(): string { return 'unknown'; } public function isSubscribedTo(Notification $notification): b { return false; } } return new UnknownUser(); final class DbUserRepository implements UserRepository 1 { 2 public function get(string $username): User 3 { 4 $userRecord = $this->db->fetchAssoc('SELECT * FROM use 5 6 if (false === $userRecord) { 7 8 } 9 10 return User::fromArray($userRecord); 11 } 12 } 13

Slide 21

Slide 21 text

$user = $userRepository->get('John'); if ($user->isSubscribedTo($notification)) { $notifier->notify($user, $notification); }

Slide 22

Slide 22 text

Checking for Special Case

Slide 23

Slide 23 text

Checking for Special Case if ($user instanceof UnknownUser) { //do something }

Slide 24

Slide 24 text

Checking for Special Case if ($user instanceof UnknownUser) { //do something } if ($user === User::unknown()) { //do something }

Slide 25

Slide 25 text

Special Case factory class User { public static function unknown(): User { static $unknownUser = null; if (null === $unknownUser) { $unknownUser = new UnknownUser(); } return $unknownUser; } }

Slide 26

Slide 26 text

Special Case object as private nested class class User { public static function unknown(): User { static $unknownUser = null; if (null === $unknownUser) { $unknownUser = new class extends User { public function username(): string { return 'unknown'; } public function isSubscribedTo(Notification $noti { return false; } }; } return $unknownUser; } }

Slide 27

Slide 27 text

Returning null from methods is bad, but passing null into methods is worse. Robert C. Martin, "Clean Code" “

Slide 28

Slide 28 text

class Order { public function __construct( Product $product, Customer $customer, ?Discount $discount ) { $this->product = $product; $this->customer = $customer; $this->discount = $discount; } } final class PremiumDiscount implements Discount { public function apply(float $productPrice): float { return $productPrice * 0.5; } }

Slide 29

Slide 29 text

?Discount $discount if (null !== $this->discount) { } class Order 1 { 2 public function __construct( 3 Product $product, 4 Customer $customer, 5 6 ) { 7 $this->product = $product; 8 $this->customer = $customer; 9 $this->discount = $discount; 10 } 11 12 public function total(): float 13 { 14 $price = $this->product->getPrice(); 15 16 17 $price = $this->discount->apply($price); 18 19 20 return $price; 21 } 22 } 23

Slide 30

Slide 30 text

Discount $discount class Order 1 { 2 public function __construct( 3 Product $product, 4 Customer $customer, 5 6 ) { 7 $this->product = $product; 8 $this->customer = $customer; 9 $this->discount = $discount; 10 } 11 } 12

Slide 31

Slide 31 text

Discount $discount class Order 1 { 2 public function __construct( 3 Product $product, 4 Customer $customer, 5 6 ) { 7 $this->product = $product; 8 $this->customer = $customer; 9 $this->discount = $discount; 10 } 11 } 12 final class NoDiscount implements Discount { public function apply(float $productPrice): float { return $productPrice; } } $order = new Order($product, $customer, new NoDiscount());

Slide 32

Slide 32 text

EXCEPTION VS SPECIAL CASE EXCEPTION VS SPECIAL CASE Special Case as default strategy instead of optional parameters Exceptions break normal ow to split business logic from error handling Special Case handles exceptional behaviour Exception emphasizes violated business rule

Slide 33

Slide 33 text

USING EXCEPTIONS USING EXCEPTIONS

Slide 34

Slide 34 text

Should be simple as: throw new \Exception('User was not found by username: ' . $usernam

Slide 35

Slide 35 text

Should be simple as: throw new \Exception('User was not found by username: ' . $usernam

Slide 36

Slide 36 text

CUSTOM EXCEPTION TYPES CUSTOM EXCEPTION TYPES bring semantics to your code emphasise exception type instead of exception message allow caller to act di erently based on Exception type

Slide 37

Slide 37 text

STRUCTURING EXCEPTIONS STRUCTURING EXCEPTIONS src/ Todo/ Exception/ Model/ User/ Exception/ Model/

Slide 38

Slide 38 text

CREATING EXCEPTION CLASSES CREATING EXCEPTION CLASSES src/ User/ Exception/ InvalidUsername.php UsernameAlreadyTaken.php UserNotFound.php final class UserNotFound extends \Exception { }

Slide 39

Slide 39 text

use App\User\Exception\UserNotFoundException; try { throw new UserNotFoundException(); } catch (UserNotFoundException $exception) { }

Slide 40

Slide 40 text

use App\User\Exception\UserNotFoundException; try { throw new UserNotFoundException(); } catch (UserNotFoundException $exception) { } use App\User\Exception\UserNotFound; try { throw new UserNotFound(); } catch (UserNotFound $exception) { }

Slide 41

Slide 41 text

COMPONENT LEVEL EXCEPTION COMPONENT LEVEL EXCEPTION TYPE TYPE

Slide 42

Slide 42 text

COMPONENT LEVEL EXCEPTION COMPONENT LEVEL EXCEPTION TYPE TYPE namespace App\User\Exception; interface ExceptionInterface { } final class InvalidUsername extends \Exception implements ExceptionInterface { } final class UserNotFound extends \Exception implements ExceptionInterface { }

Slide 43

Slide 43 text

use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ServerException; use GuzzleHttp\Exception\GuzzleException; //marker interface try { //code that can emit exceptions } catch (ClientException $ex) { //... } catch (ServerException $ex) { //... } catch (GuzzleException $ex) { //... }

Slide 44

Slide 44 text

FORMATTING EXCEPTION FORMATTING EXCEPTION MESSAGES MESSAGES

Slide 45

Slide 45 text

FORMATTING EXCEPTION FORMATTING EXCEPTION MESSAGES MESSAGES throw new UserNotFound(sprintf( 'User was not found by username: %s', $username ));

Slide 46

Slide 46 text

FORMATTING EXCEPTION FORMATTING EXCEPTION MESSAGES MESSAGES throw new UserNotFound(sprintf( 'User was not found by username: %s', $username )); throw new InsufficientPermissions(sprintf( 'You do not have permission to %s %s with the id: %s', $privilege, get_class($entity), $entity->getId() ));

Slide 47

Slide 47 text

Encapsulate formatting into Exception classes final class UserNotFound extends \Exception implements ExceptionI { public static function byUsername(string $username): self { return new self(sprintf( 'User was not found by username: %s', $username )); } }

Slide 48

Slide 48 text

Named Constructors communicate the intent throw UserNotFound::byUsername($username);

Slide 49

Slide 49 text

Coherent exceptional conditions throw TodoNotOpen::triedToSetDeadline($deadline, $this->status); throw TodoNotOpen::triedToMarkAsCompleted($this->status);

Slide 50

Slide 50 text

PROVIDE CONTEXT PROVIDE CONTEXT

Slide 51

Slide 51 text

PROVIDE CONTEXT PROVIDE CONTEXT final class UserNotFound extends \Exception implements ExceptionI { private string $username; public static function byUsername(string $username): self { $ex = new self(sprintf('User was not found by username: % $ex->username = $username; return $ex; } public function username(): string { return $this->username; } }

Slide 52

Slide 52 text

EXCEPTION WRAPPING EXCEPTION WRAPPING

Slide 53

Slide 53 text

EXCEPTION WRAPPING EXCEPTION WRAPPING try { return $this->toResult( $this->httpClient->request('GET', '/users') ); } catch (ConnectException $ex) { throw ApiNotAvailable::reason($ex); } 1 2 3 4 5 6 7

Slide 54

Slide 54 text

EXCEPTION WRAPPING EXCEPTION WRAPPING try { return $this->toResult( $this->httpClient->request('GET', '/users') ); } catch (ConnectException $ex) { throw ApiNotAvailable::reason($ex); } 1 2 3 4 5 6 7 final class ApiNotAvailable extends \Exception implements Exce { public static function reason(ConnectException $error): se { return new self( 'API is not available', 0, $error //preserve previous error ); } } 1 2 3 4 5 6 7 8 9 10 11

Slide 55

Slide 55 text

EXCEPTION WRAPPING EXCEPTION WRAPPING try { return $this->toResult( $this->httpClient->request('GET', '/users') ); } catch (ConnectException $ex) { throw ApiNotAvailable::reason($ex); } 1 2 3 4 5 6 7 final class ApiNotAvailable extends \Exception implements Exce { public static function reason(ConnectException $error): se { return new self( 'API is not available', 0, $error //preserve previous error ); } } 1 2 3 4 5 6 7 8 9 10 11 $error //preserve previous error final class ApiNotAvailable extends \Exception implements Exce 1 { 2 public static function reason(ConnectException $error): se 3 { 4 return new self( 5 'API is not available', 6 0, 7 8 ); 9 } 10 } 11

Slide 56

Slide 56 text

RETROSPECT RETROSPECT 1. create custom, cohesive Exception types 2. introduce component-level exception type 3. use Named Constructors to encapsulate message formatting and express the intent 4. capture & provide the context of the exceptional condition 5. apply exception wrapping to rethrow more informative exception

Slide 57

Slide 57 text

ERROR HANDLING ERROR HANDLING

Slide 58

Slide 58 text

WHEN TO CATCH EXCEPTIONS? WHEN TO CATCH EXCEPTIONS?

Slide 59

Slide 59 text

WHEN TO CATCH EXCEPTIONS? WHEN TO CATCH EXCEPTIONS? Do NOT catch exceptions unless you can handle the problem so that the application continues to work

Slide 60

Slide 60 text

CENTRAL ERROR HANDLER CENTRAL ERROR HANDLER Wraps the entire system to handle any uncaught exceptions from a single place

Slide 61

Slide 61 text

CHALLENGES CHALLENGES user experience security logging

Slide 62

Slide 62 text

CHALLENGES CHALLENGES user experience security logging adaptability

Slide 63

Slide 63 text

EXISTING SOLUTIONS EXISTING SOLUTIONS

Slide 64

Slide 64 text

EXISTING SOLUTIONS EXISTING SOLUTIONS - stack-based error handling, pretty error page, handlers for di erent response formats (JSON, XML) Whoops

Slide 65

Slide 65 text

EXISTING SOLUTIONS EXISTING SOLUTIONS - stack-based error handling, pretty error page, handlers for di erent response formats (JSON, XML) - di erent formatting strategies (HTML, JSON, CLI), logging handler, non- blocking errors Whoops BooBoo

Slide 66

Slide 66 text

Using Whoops final class ErrorHandlerFactory { public function __invoke(ContainerInterface $container) { $whoops = new \Whoops\Run(); if (\Whoops\Util\Misc::isAjaxRequest()) { $whoops->pushHandler(new JsonResponseHandler()); } elseif (\Whoops\Util\Misc::isCommandLine()) { $whoops->pushHandler(new CommandLineHandler()); } else { $whoops->pushHandler(new PrettyPageHandler()); } $whoops->pushHandler(new SetHttpStatusCodeHandler()); $whoops->pushHandler(new LogHandler($container->get('Logg return $whoops; } }

Slide 67

Slide 67 text

src/bootstrap.php public/index.php bin/app //... initialize DI container $container->get(\Whoops\Run::class)->register(); return $container; $container = require __DIR__ . '/../src/bootstrap.php'; $container->get('App\Web')->run(); $container = require __DIR__ . '/../src/bootstrap.php'; $container->get('App\Console')->run();

Slide 68

Slide 68 text

Logging errors final class LogHandler extends Handler { public function handle() { $error = $this->getException(); if ($error instanceof DontLog) { return self::DONE; } $this->logger->error($error->getMessage(), [ 'exception' => $error, ]); return self::DONE; } }

Slide 69

Slide 69 text

final class UserNotFound extends \Exception implements ExceptionInterface, DontLog { //... }

Slide 70

Slide 70 text

Setting HTTP status code final class SetHttpStatusCodeHandler extends Handler { public function handle() { $error = $this->getException(); $httpStatusCode = ($error instanceof ProvidesHttpStatusCode) ? $error->getHttpStatusCode() : 500; $this->getRun()->sendHttpCode($httpStatusCode); return self::DONE; } }

Slide 71

Slide 71 text

interface ProvidesHttpStatusCode { public function getHttpStatusCode(): int; } final class UserNotFound extends \Exception implements ExceptionInterface, DontLog, ProvidesHttpStatusCode { //... public function getHttpStatusCode(): int { return 404; } }

Slide 72

Slide 72 text

The OCP (Open­Closed Principle) is one of the driving forces behind the architecture of systems. The goal is to make the system easy to extend without incurring a high impact of change. Robert C. Martin, "Clean Architecture" “

Slide 73

Slide 73 text

TEST EXCEPTIONAL TEST EXCEPTIONAL BEHAVIOUR BEHAVIOUR a.k.a. Negative Testing

Slide 74

Slide 74 text

TESTING EXCEPTIONS WITH TESTING EXCEPTIONS WITH PHPUNIT PHPUNIT class TodoTest extends TestCase { /** * @test */ public function it_throws_exception_on_reopening_if_incomp { $todo = Todo::from('Book flights', TodoStatus::OPEN()) $this->expectException(CannotReopenTodo::class); $todo->reopen(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Slide 75

Slide 75 text

TESTING EXCEPTIONS WITH TESTING EXCEPTIONS WITH PHPUNIT PHPUNIT class TodoTest extends TestCase { /** * @test */ public function it_throws_exception_on_reopening_if_incomp { $todo = Todo::from('Book flights', TodoStatus::OPEN()) $this->expectException(CannotReopenTodo::class); $todo->reopen(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 $this->expectException(CannotReopenTodo::class); $todo->reopen(); class TodoTest extends TestCase 1 { 2 /** 3 * @test 4 */ 5 public function it_throws_exception_on_reopening_if_incomp 6 { 7 $todo = Todo::from('Book flights', TodoStatus::OPEN()) 8 9 10 11 12 } 13 } 14

Slide 76

Slide 76 text

ARRANGE-ACT-ASSERT ARRANGE-ACT-ASSERT 1. initialize SUT/prepare inputs 2. perform action 3. verify outcomes

Slide 77

Slide 77 text

class TodoTest extends TestCase { /** * @test */ public function it_gets_completed() { $todo = Todo::from('Book flights', TodoStatus::OPEN()); $todo->complete(); $this->assertTrue($todo->isCompleted()); } }

Slide 78

Slide 78 text

/** * @test */ public function it_throws_exception_on_reopening_if_incomplete() { $todo = Todo::from('Book flights', TodoStatus::OPEN()); try { $todo->reopen(); $this->fail('Exception should have been raised'); } catch (CannotReopenTodo $ex) { $this->assertSame( 'Tried to reopen todo, but it is not completed.', $ex->getMessage() ); } }

Slide 79

Slide 79 text

Thank you Thank you Drop me some feedback and make this presentation better · joind.in/talk/8a8d6 @nikolaposa blog.nikolaposa.in.rs