Boom

The Boom class provides a fluent interface for generating HTTP error responses. It standardizes error output, ensuring your API returns consistent JSON structures with appropriate status codes and details.

Why Use Boom?

Managing raw HTTP headers and JSON encoding manually leads to inconsistency. Boom abstracts this into descriptive static methods. Instead of remembering that "402" is "Payment Required", you simply call Boom::paymentRequired().

Factory Methods

All factory methods accept two optional arguments: a custom message string and an array of additional details.

4xx Client Errors
badRequest() 400
unauthorized() 401
paymentRequired() 402
forbidden() 403
notFound() 404
methodNotAllowed() 405
notAcceptable() 406
conflict() 409
gone() 410
payloadTooLarge() 413
locked() 423
tooManyRequests() 429
5xx Server Errors
internal() 500
notImplemented() 501
badGateway() 502
serviceUnavailable() 503
gatewayTimeout() 504
Utilities
toResponse(): void
Sends headers + JSON & exits.
isBoom($err): bool
Checks instance type.
create(code, msg, details)
Manual instantiation.

Usage Examples

1. Basic Validation Error

<?php
use PP\Headers\Boom;
use PP\Validator;

$id = $params->id ?? null;

// Return 400 Bad Request immediately
if (!Validator::int($id)) {
    Boom::badRequest('Invalid user ID provided.', ['received_id' => $id])->toResponse();
}
?>

Output: {"statusCode": 400, "error": "Bad Request", "details": {"received_id": "abc"}}

2. Method Protection

<?php
use PP\Headers\Boom;
use PP\Request;

if (!Request::$isPost) {
    Boom::methodNotAllowed('Only POST requests are accepted here.')->toResponse();
}
?>

3. Database Exception Handling

<?php
use PP\Headers\Boom;
use PP\Prisma\Classes\Prisma;

try {
    $user = Prisma::getInstance()->user->create([
        'data' => ['email' => 'duplicate@example.com']
    ]);
} catch (PDOException $e) {
    if ($e->getCode() === '23000') {
        // Handle Unique Constraint
        Boom::conflict('Email already exists.')->toResponse();
    }
    
    // Handle General Failure
    Boom::internal('Database error', ['trace' => $e->getMessage()])->toResponse();
}
?>