PHP code example of maatify / exceptions

1. Go to this page and download the library: Download maatify/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/ */

    

maatify / exceptions example snippets


use Maatify\Exceptions\Exception\Validation\InvalidArgumentMaatifyException;

throw new InvalidArgumentMaatifyException('The email format is invalid.');
// Result:
// Category: VALIDATION
// HTTP Status: 400
// Error Code: INVALID_ARGUMENT

use Maatify\Exceptions\Exception\BusinessRule\BusinessRuleMaatifyException;
use Maatify\Exceptions\Exception\System\DatabaseConnectionMaatifyException;

try {
    // Simulate a critical database failure (System / 503)
    throw new DatabaseConnectionMaatifyException('Connection timeout');
} catch (DatabaseConnectionMaatifyException $e) {
    // Attempting to wrap it in a "softer" business exception
    // Note: BusinessRuleMaatifyException is abstract, so we use an anonymous class for this example
    throw new class('Unable to process order', 0, $e) extends BusinessRuleMaatifyException {};
}

// RESULT:
// The final exception will report:
// Category: SYSTEM (Escalated from BusinessRule)
// HTTP Status: 503 (Escalated from 422)
// This ensures monitoring tools see the root cause (System Failure), not a generic Business Rule error.

use Maatify\Exceptions\Application\Error\ErrorSerializer;
use Maatify\Exceptions\Application\Error\DefaultThrowableToError;
use Maatify\Exceptions\Application\Format\JsonErrorFormatter;

$serializer = new ErrorSerializer(
    new DefaultThrowableToError(),
    new JsonErrorFormatter()
);

try {
    // ... application logic
} catch (\Throwable $t) {
    $response = $serializer->serialize($t);
    
    // Send to client
    http_response_code($response->getStatus());
    header('Content-Type: ' . $response->getContentType());
    echo json_encode($response->getBody());
}