Boom

The Boom class provides a set of utility methods for generating HTTP error responses with appropriate status codes and messages. It is useful for handling errors in a consistent and user-friendly manner across an application.

Purpose

The Boom class simplifies the process of generating error responses in an application. It provides a set of static methods for creating responses with common HTTP status codes and messages. This can help improve the user experience by providing clear and consistent error messages when something goes wrong.

Methods

Each method in the Boom class returns a new instance of the class with the specified status code, error message, and additional details. The toResponse method sends the error response to the client and terminates the script execution.

  • static badRequest(string $message = 'Bad Request', array $details = []): Returns a new instance of the Boom class with a 400 Bad Request status code.
  • static unauthorized(string $message = 'Unauthorized', array $details = []): Returns a new instance of the Boom class with a 401 Unauthorized status code.
  • static paymentRequired(string $message = 'Payment Required', array $details = []): Returns a new instance of the Boom class with a 402 Payment Required status code.
  • static forbidden(string $message = 'Forbidden', array $details = []): Returns a new instance of the Boom class with a 403 Forbidden status code.
  • static notFound(string $message = 'Not Found', array $details = []): Returns a new instance of the Boom class with a 404 Not Found status code.
  • static methodNotAllowed(string $message = 'Method Not Allowed', array $details = []): Returns a new instance of the Boom class with a 405 Method Not Allowed status code.
  • static notAcceptable: Returns a new instance of the Boom class with a 406 Not Acceptable status code.
  • static internal(string $message = 'Internal Server Error', array $details = []): Returns a new instance of the Boom class with a 500 Internal Server Error status code.
  • public function toResponse(): void: Sends the HTTP error response and terminates the script.
  • static function isBoom($error): Checks if the given error is an instance of the Boom class.
  • public function getStatusCode(): Returns the HTTP status code of the error response.
  • public function getMessage(): Returns the error message of the error response.
  • public function getDetails(): Returns the additional details of the error response.

Usage

The Boom class can be used to generate error responses in a consistent and user-friendly manner. Here is an example of how to use the Boom class to handle errors in a PHP application:

<?php

  use Lib\Headers\Boom;
  use Lib\Validator;
  
  $id = $params->id ?? null;
  
  if (!$isPost && !Validator::int($id)) {
      Boom::badRequest('Invalid user ID.')->toResponse();
  }

In this example, the Boom::badRequest method is used to generate a 400 Bad Request error response with the message 'Invalid user ID.'. If the user ID is not an integer, the error response is sent to the client using the toResponse method.

<?php
  use Lib\Headers\Boom;
  
  if (!$isPost) {
    // Respond with a 405 Method Not Allowed error
    Boom::methodNotAllowed('Method Not Allowed')->toResponse();
  } else {
    // Process the request
  }

In this example, the Boom::methodNotAllowed method is used to generate a 405 Method Not Allowed error response. If the request is not a POST request, the error response is sent to the client using the toResponse method.

Note: Always use the toResponse method to send the error response to the client. This ensures that the response is properly formatted and the script execution is terminated correctly.

<?php

  use Lib\Prisma\Classes\Prisma;
  use Lib\Validator;
  use Lib\Headers\Boom;
  use Lib\Auth\Auth;
  
  $prisma = Prisma::getInstance();
  $auth = Auth::getInstance();
  
  if (!$auth->isAuthenticated()) {
      Boom::unauthorized('Unauthorized')->toResponse();
  }
  
  $name = $params->name ?? null;
  $email = $params->email ?? null;
  $emailValidated = Validator::withRules($email, 'email|required|endsWith:.org');
  
  if ($isPost && Validator::string($name) && $emailValidated === true) {
      try {
          $user = $prisma->user->create([
              'data' => [
                  'name' => $name,
                  'email' => $email,
              ]
          ]);
  
          echo json_encode($user);
      } catch (PDOException $e) {
          // Check for unique constraint violation
          if ($e->getCode() === '23000') {
            Boom::badRequest('Email already exists in DB', ['name' => $name, 'email' => $email, 'emailValidated' => $emailValidated])->toResponse();
          } else {
              // Handle other database-related errors
              Boom::internal('Database error occurred', ['error' => $e->getMessage()])->toResponse();
          }
      } catch (Exception $e) {
          Boom::internal('An unexpected error occurred', ['error' => $e->getMessage()])->toResponse();
      }
  } else {
      Boom::badRequest('Invalid request', ['name' => $name, 'email' => $email, 'emailValidated' => $emailValidated])->toResponse();
  }

In this example, the Boom class is used to handle various error scenarios in a user registration process. If the user is not authenticated, a 401 Unauthorized error is returned. If the request is not a POST request or the input data is invalid, a 400 Bad Request error is returned. If a database error occurs during user creation, a 500 Internal Server Error is returned with additional details about the error.