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.
Sends headers + JSON & exits.
Checks instance type.
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();
}
?>