Exceptions
Overview of Laravel Exceptions in ECOM-Api
The Exceptions directory in the ECOM-Api project is designed to handle and manage various types of errors that occur within the application. This directory includes custom exception classes for specific error scenarios and a global exception handler that integrates with external services for error reporting.
Table of Contents
OrderValidationException.php
The OrderValidationException class is a custom exception designed to handle errors that occur during order validation within the Laravel E-Commerce API. This exception provides a structured way to capture and manage validation issues specific to orders.
Purpose
In an e-commerce system, order validation is crucial to ensure that all necessary data is present and correct before processing an order. Validation errors can arise due to various reasons, such as missing required fields, invalid data formats, or business rule violations. The OrderValidationException class helps to encapsulate these errors in a way that is easy to handle and communicate.
Key Features
- Custom Error Storage: This exception allows for storing an array of validation errors that are associated with the order. This makes it easy to pass detailed error information through the exception.
- Error Retrieval: Provides a method to retrieve the stored validation errors, which can be used for logging, debugging, or returning meaningful error responses to API consumers.
Implementation
Here is a breakdown of the OrderValidationException class:
<?php
namespace App\Exceptions;
use Exception;
class OrderValidationException extends Exception
{
/**
* @var array
*/
private $errors;
/**
* OrderValidationException constructor.
* @param array $errors
*/
public function __construct($errors = [])
{
$this->errors = $errors;
}
/**
* Get the validation errors.
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
}
Handler.php
The Handler class in this Laravel project is responsible for managing and reporting exceptions that occur within the application. This class extends Laravel's built-in ExceptionHandler and includes custom logic to integrate with Google Cloud Platform (GCP) for error reporting.
Overview
The Handler class provides a centralized mechanism for handling exceptions and ensures that errors are reported efficiently. It includes functionality for:
- Exception Reporting: Determines which exceptions should be reported and sends error details to GCP Error Reporting.
- Exception Filtering: Configures which types of exceptions should not be reported and which request inputs should be excluded from validation flash data.
Key Features
- Exception Reporting to GCP: Integrates with Google Cloud Logging to report exceptions, including optional metadata for better context.
- Exception Filtering: Allows for customization of which exceptions and request inputs are excluded from reporting and flashing.
Implementation
Here’s a detailed breakdown of the Handler class:
<?php
namespace App\Exceptions;
use Google\Cloud\Core\Report\SimpleMetadataProvider;
use Google\Cloud\ErrorReporting\Bootstrap;
use Google\Cloud\Logging\LoggingClient;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
// Add exception types here that you don't want to report
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
if ($e instanceof \Toolstation\Core\BaseException) {
// Custom base exception check
if (! $e->shouldReport()) {
return;
}
}
$this->reportToGcpErrorReporting($e);
});
}
/**
* Report the exception to Google Cloud Platform's error reporting service.
*
* @param Throwable $exception
* @return void
*/
private function reportToGcpErrorReporting(Throwable $exception)
{
if (config('platform.gcp.logging.enabled') === true) {
$psrLogger = (new LoggingClient(config('platform.gcp.service_account') ? [
'keyFile' => config('platform.gcp.service_account'),
] : []))->psrLogger('app-error', [
'batchEnabled' => false,
'debugOutput' => false,
'batchOptions' => ['numWorkers' => 2],
'metadataProvider' => new SimpleMetadataProvider(
[],
config('platform.gcp.cloud_project'),
config('app.name'),
config('app.version'),
),
]);
Bootstrap::init($psrLogger);
Bootstrap::exceptionHandler($exception);
}
}
}
BankTransferDetailsException
The BankTransferDetailsException class is a custom exception designed for handling specific errors related to bank transfer details within the TradeCredit module of the Laravel application. This class extends the base \Exception class and provides a standardized way to signal issues that arise during bank transfer operations.
Purpose
In financial applications, especially those dealing with trade credit and bank transactions, it is essential to handle errors in a precise and informative manner. The BankTransferDetailsException class is intended to encapsulate errors associated with bank transfer details. This ensures that errors are reported with a clear, descriptive message, facilitating easier debugging and better user feedback.
By using a custom exception, developers can distinguish errors related to bank transfers from other types of exceptions, allowing for more granular error handling and reporting.
Key Features
- Custom Error Message: The exception is initialized with a predefined error message that indicates there was an issue with bank transfer details. This message is set to
'There was an error with Bank transfer details', providing a clear explanation of the problem. - Extendability: The class extends the base
\Exceptionclass, which means it inherits all standard exception functionalities while adding a specific context for bank transfer errors.
Implementation
Here’s the full implementation of the BankTransferDetailsException class:
<?php
namespace App\Exceptions\TradeCredit;
class BankTransferDetailsException extends \Exception
{
/**
* BankTransferDetailsException constructor.
*/
public function __construct()
{
parent::__construct('There was an error with Bank transfer details');
}
}
BankTransferException
The BankTransferException class is a custom exception designed to handle errors specifically related to bank transfer operations within the TradeCredit module of the Laravel application. It extends the base \Exception class and provides a specific error message for issues encountered during bank transfers.
Purpose
In financial systems, errors during bank transfers need to be handled carefully to ensure that users are informed about issues and that the system can respond appropriately. The BankTransferException class allows for a clear and consistent way to report and handle such errors. By using a dedicated exception class, you can separate bank transfer errors from other types of exceptions, leading to better error management and more readable code.
Key Features
- Custom Error Message: The exception is initialized with a specific error message:
'There was an error with Bank transfer'. This message provides clarity on the nature of the problem and helps in diagnosing issues related to bank transfers. - Extensibility: As it extends the base
\Exceptionclass, it inherits all standard exception functionalities while providing additional context specific to bank transfer errors.
Implementation
Here’s the full implementation of the BankTransferException class:
<?php
namespace App\Exceptions\TradeCredit;
class BankTransferException extends \Exception
{
/**
* BankTransferException constructor.
*/
public function __construct()
{
parent::__construct('There was an error with Bank transfer');
}
}
BankTransferStatusException
The BankTransferStatusException class is a custom exception used within the TradeCredit module of the Laravel application. It is designed to handle errors related to unexpected or unknown bank transfer statuses. This class extends the base \Exception class and provides a specific error message that includes the status type received.
Purpose
In financial applications, it is crucial to handle various statuses that bank transfers can have. When an unexpected or unknown status type is encountered, it is important to report this issue clearly to facilitate debugging and ensure proper error handling. The BankTransferStatusException class helps in capturing and reporting such errors with a descriptive message that includes the problematic status type.
Key Features
- Dynamic Error Message: The exception is initialized with a dynamic error message that includes the unknown status type. This message is formatted as
'Unknown status type ('.$status.') received.', providing a clear indication of what went wrong. - Extensibility: By extending the base
\Exceptionclass, it inherits standard exception functionalities while adding specific context for errors related to bank transfer statuses.
Implementation
Here’s the full implementation of the BankTransferStatusException class:
<?php
namespace App\Exceptions\TradeCredit;
class BankTransferStatusException extends \Exception
{
/**
* BankTransferStatusException constructor.
*
* @param string $status The unknown status type that was received
*/
public function __construct($status)
{
parent::__construct('Unknown status type ('.$status.') received.');
}
}