PHP code example of smuuf / better-php-exceptions

1. Go to this page and download the library: Download smuuf/better-php-exceptions library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

smuuf / better-php-exceptions example snippets


use \Smuuf\BetterExceptions\BetterException;

try {
	...
} catch (\Throwable $ex) {
	$better = BetterException::from($ex);
	...
}




declare(strict_types=1);

terException;

// Yes, it has a wrong return type.
function join_strings(string $a, ?string $b): ?int {
	return "{$a} - {$b}";
}

try {

	// Argument type error.
	join_strings('first', 123);

} catch (\TypeError $ex) {

	// Convert the generic TypeError to something more usable.
	$better = BetterException::from($ex);

	// Now we know that it was an argument type error.
	var_dump($better);
	// object(Smuuf\BetterExceptions\Types\ArgumentTypeError) ...

	// We know that 'string' or 'null' was expected.
	var_dump($better->getExpected());
	// array(2) {
	//   [0]=>
	//   string(6) "string"
	//   [1]=>
	//   string(4) "null"
	// }

	// We know that 'int' was actually passed.
	var_dump($better->getActual());
	// string(3) "int"

	// And it was the second argument that was wrong.
	var_dump($better->getArgumentIndex());
	// int(2)

}

try {

	// Return type error.
	join_strings('first', 'second');

} catch (\TypeError $ex) {

	// Convert the generic TypeError to something more usable.
	$better = BetterException::from($ex);

	// Now we know that it was a return type error.
	var_dump($better);
	// object(Smuuf\BetterExceptions\Types\ReturnTypeError) ...

	// We know that 'int' or 'null' was expected.
	var_dump($better->getExpected());
	// array(2) {
	//   [0]=>
	//   string(3) "int"
	//   [1]=>
	//   string(4) "null"
	// }

	// We know that 'string' was actually passed.
	var_dump($better->getActual());
	// string(6) "string"

}