bytestechnolabs/custom-exception-handler
Laravel package for configurable exception handling: map exception classes to custom messages, HTTP status codes, and extra response data via config. Includes helper to add custom data dynamically during catch blocks for consistent API error responses.
Installation
composer require bytestechnolabs/custom-exception-handler
Publish the config file (if provided):
php artisan vendor:publish --provider="ByteScode\CustomExceptionHandler\CustomExceptionHandlerServiceProvider"
Basic Usage
Register the package in config/app.php under providers:
ByteScode\CustomExceptionHandler\CustomExceptionHandlerServiceProvider::class,
First Use Case
Extend Laravel’s default exception handling by overriding App\Exceptions\Handler.php:
use ByteScode\CustomExceptionHandler\CustomExceptionHandler;
public function render($request, Throwable $exception)
{
return CustomExceptionHandler::handle($request, $exception);
}
Default Configuration
Check config/custom-exception-handler.php for:
404, 500).Exception Mapping
Define custom responses per exception type in config/custom-exception-handler.php:
'mappings' => [
\App\Exceptions\ValidationException::class => [
'status' => 422,
'format' => 'json',
'template' => 'errors.validation',
],
],
Dynamic Handling Use middleware to inject context (e.g., user roles):
public function handle($request, Closure $next)
{
$request->merge(['user_role' => auth()->user()->role]);
return $next($request);
}
API vs. Web Responses Differentiate responses based on request type:
if ($request->wantsJson()) {
return CustomExceptionHandler::formatJson($exception);
}
return CustomExceptionHandler::formatHtml($exception);
Logging Integration Log exceptions conditionally:
if (config('custom-exception-handler.log_level') === 'critical') {
Log::critical($exception);
}
template config to render error views in your frontend build.CustomExceptionHandler in PHPUnit:
$handler = $this->app->make(CustomExceptionHandler::class);
$response = $handler->handle($request, new \Exception('Test'));
if ($exception instanceof \Illuminate\Bus\QueueingFailedJob) {
// Custom logic for queue failures
}
Config Overrides
App\Exceptions\Handler. Use a unique namespace (e.g., App\Handlers\CustomExceptionHandler).$config = array_merge(
require __DIR__.'/custom-exception-handler.php',
config('custom-exception-handler', [])
);
Circular Dependencies
App\Exceptions\Handler, ensure it’s autoloaded before the package’s service provider.config/app.php.Performance
render() can slow responses.Missing Templates
errors.validation) is missing, the handler may throw a ViewNotFoundException.CustomExceptionHandler::setFallbackTemplate('errors.default');
config/custom-exception-handler.php:
'debug' => env('APP_DEBUG', false),
dd($exception) in render() to inspect the exception object structure.Custom Formats Extend the handler to support new formats (e.g., XML):
CustomExceptionHandler::extend('xml', function ($exception) {
return response()->xml($exception->getMessage());
});
Event Listeners
Listen for exception events to pre-process exceptions:
Event::listen(ExceptionOccurred::class, function ($event) {
$event->exception->setCustomAttribute('user_id', auth()->id());
});
Localization Override error messages via language files:
// resources/lang/en/errors.php
return [
'validation' => 'Custom validation error message.',
];
Then reference in config:
'mappings' => [
\App\Exceptions\ValidationException::class => [
'message' => __('errors.validation'),
],
],
Testing Edge Cases Test with:
$exception->getPrevious()).$request->header('Accept-Language')).How can I help you explore Laravel packages today?