Search by

dwiky-danov / business-error-handler

danovcode

Framework-agnostic global error handling with safe API responses and optional Kibana logging.

Package info

github.com/danovcode/laravel-error-handling

pkg:composer/dwiky-danov/business-error-handler

Statistics

Installs: 33

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v4.1.5 2026-11-21 15:47 UTC

This package is auto-updated.

Last update: 2026-11-21 15:48:17 UTC


README

πŸ›‘οΈ Laravel Error Handling

One handler for every exception: consistent JSON responses, safe in production, ready for Kibana.

PHP Laravel License

Background Β· Install Β· Custom messages Β· Kibana logging Β· FAQ

πŸ“‘ Table of contents

😩 Background

Tired of handling exceptions one by one? A try/catch in every controller, a different JSON shape per endpoint, stack traces leaking to production, and no way to trace one failing request across your logs.

❌ Before

try {
    $order = Order::findOrFail($id);
} catch (ModelNotFoundException $e) {
    return response()->json(['error' => 'not found'], 404);
} catch (\Throwable $e) {
    Log::error($e);
    return response()->json(['msg' => $e->getMessage()], 500);
}

βœ… After

$order = Order::findOrFail($id);
// β†’ 404 {"status":false,"message":"No Result for Query [Order].","correlation_id":"…"}

✨ Features

  • 🧾 One JSON shape for every error: status, message, correlation_id
  • πŸ”’ Production-safe: raw exception messages and stack traces are never returned
  • 🧩 BusinessValidationException with an optional data payload β†’ 422
  • πŸ“ Laravel ValidationException β†’ first message, plus the full validation map when there are several
  • 🏷️ Custom message per exception class (with a {model} placeholder)
  • πŸ”— Correlation ID reused from X-Correlation-ID or generated (UUID v4), plus optional request/response logging to Kibana (Elasticsearch)

πŸ”€ How it works

flowchart LR
    A[Request /api/*] --> B[Controller]
    B -- throws --> C{Exception}
    C --> D[ErrorHandler::render]
    D --> E[Safe JSON + status code]
    E --> F[X-Correlation-ID header]
    E --> G[LogRequestResponse middleware]
    G -- kibana_logging=true --> H[(Elasticsearch / Kibana)]
    G -- false --> I[Laravel log]
Loading

πŸš€ Installation

1️⃣ Install the package

composer require dwiky-danov/business-error-handler

The service provider is auto-discovered by Laravel.

Package not found on Packagist?

Install it straight from GitHub by adding a VCS repository to your app's composer.json:

"repositories": [
    { "type": "vcs", "url": "https://github.com/danovcode/laravel-error-handling" }
]

Then run composer require dwiky-danov/business-error-handler again.

2️⃣ Generate the config

php artisan make:errorhandler
# or, with Kibana logging switched on:
php artisan make:errorhandler --logkibana

This creates config/error-handler.php:

return [
    'environment' => env('APP_ENV', 'production'),
    'kibana_logging' => false,
    'kibana_url' => env('KIBANA_URL', 'http://localhost:9200/error-handler/_doc'),
    'default_message' => 'Internal Server Error',
    'exception_messages' => [],
];

Warning

environment only accepts development or production. The generated config uses env('APP_ENV'), so APP_ENV=local (or testing, staging, …) throws on boot. See the FAQ for a one-line mapping.

Note

The command refuses to overwrite an existing config/error-handler.php. Delete the file first if you want to regenerate it.

3️⃣ Register it in bootstrap/app.php

->withExceptions(function (Exceptions $exceptions): void {
    ErrorHandler::register(config('error-handler'));

    $exceptions->render(function (Throwable $exception, Request $request) {
        if (! $request->is('api/*')) {
            return null; // let Laravel handle web routes
        }

        $status = match (true) {
            $exception instanceof BusinessValidationException => 422,
            $exception instanceof ValidationException => $exception->status,
            $exception instanceof AuthenticationException => 401,
            $exception instanceof ModelNotFoundException => 404,
            $exception instanceof HttpExceptionInterface => $exception->getStatusCode(),
            $exception instanceof BadRequestException => $exception->getStatusCode(),
            default => 500,
        };
        $payload = ErrorHandler::render($exception);

        return response()->json($payload, $status)
            ->header('X-Correlation-ID', $payload['correlation_id']);
    });
})
πŸ“„ Show the full bootstrap/app.php with all imports
<?php

use BusinessErrorHandler\BusinessValidationException;
use BusinessErrorHandler\ErrorHandler;
use BusinessErrorHandler\Http\BadRequestException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        ErrorHandler::register(config('error-handler'));

        $exceptions->render(function (Throwable $exception, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }

            $status = match (true) {
                $exception instanceof BusinessValidationException => 422,
                $exception instanceof ValidationException => $exception->status,
                $exception instanceof AuthenticationException => 401,
                $exception instanceof ModelNotFoundException => 404,
                $exception instanceof HttpExceptionInterface => $exception->getStatusCode(),
                $exception instanceof BadRequestException => $exception->getStatusCode(),
                default => 500,
            };
            $payload = ErrorHandler::render($exception);

            return response()->json($payload, $status)
                ->header('X-Correlation-ID', $payload['correlation_id']);
        });
    })
    ->create();

Tip

Done! Throw anything in an API route and you get a consistent JSON response. The package also ships ready-made HTTP exceptions in BusinessErrorHandler\Http: BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), MethodNotAllowedException (405) and TooManyRequestsException (429).

🐘 Not using Laravel?

The core is framework-agnostic. Register it once during bootstrap and it installs global exception, error and shutdown handlers that print the JSON response and set the status code and X-Correlation-ID header:

use BusinessErrorHandler\ErrorHandler;

ErrorHandler::register([
    'environment' => 'production', // or 'development'
]);

Pass 'logger' => new \BusinessErrorHandler\Logger\MonologLogger($psrLogger) (or any BusinessErrorHandler\Logger\LoggerInterface implementation) to send structured error logs elsewhere.

πŸ“¦ Example responses

Show request β†’ response examples

Business rule (422)

throw new BusinessValidationException('Insufficient balance.', data: [
    'available_balance' => 50,
    'required_amount' => 75,
]);
{
    "status": false,
    "message": "Insufficient balance.",
    "correlation_id": "…",
    "data": { "available_balance": 50, "required_amount": 75 }
}

data accepts any JSON-encodable value. Leave it out and the data key is omitted; pass data: null explicitly and you get "data": null.

Validation (422): message is the first validation message. The validation map appears only when there is more than one message.

{
    "status": false,
    "message": "The email field is required.",
    "correlation_id": "…",
    "validation": {
        "email": ["The email field is required."],
        "password": ["The password field must be at least 8 characters."]
    }
}

Not found (404)

curl -H "X-Correlation-ID: test-123" https://your-app.test/api/orders/999999
{ "status": false, "message": "No Result for Query [Order].", "correlation_id": "test-123" }

Unexpected error (500, production)

{ "status": false, "message": "Internal Server Error", "correlation_id": "…" }

Same error in development shows the raw exception message and adds an exception block:

{
    "status": false,
    "message": "Undefined variable $total",
    "correlation_id": "…",
    "exception": {
        "class": "ErrorException",
        "message": "Undefined variable $total",
        "file": "/var/www/app/Http/Controllers/OrderController.php",
        "line": 42,
        "trace": "#0 …"
    }
}

πŸ“ Custom messages

Set a message per exception class in config/error-handler.php:

use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;

'exception_messages' => [
    ModelNotFoundException::class  => ['message' => '{model} not found.'],
    QueryException::class          => ['message' => 'A database error occurred.'],
    AuthenticationException::class => ['message' => 'Please log in first.'],
    '*'                            => ['message' => 'Something went wrong.'], // optional catch-all
],
  • Matching also checks parent classes and interfaces, so one entry can cover a whole family.
  • Placeholders for model errors: {model}, {model_name}, :model, [Model Name]. App\Models\Balance becomes Balance.
  • Custom messages are shown in production, so keep them user-safe.
πŸ”’ Which message wins? (priority order)
  1. BusinessValidationException β†’ its own message
  2. ModelNotFoundException wrapped inside another exception (e.g. NotFoundHttpException) β†’ resolved as the model error
  3. exception_messages[ExactClass] β†’ parent classes β†’ interfaces
  4. exception_messages['*'] (catch-all)
  5. First validation message (ValidationException)
  6. Built-in default message (see table below)
  7. development: raw exception message / production: default_message

Caution

'*' is checked before validation messages, so a catch-all also replaces your validation messages.

πŸ“‹ Built-in default messages

Defaults are matched by short class name, first on the exception itself and then on its parent classes, so they apply to Laravel, Symfony, PHP and this package's own Http\* exceptions alike.

Exception (short name) Message
ModelNotFoundException No Result for Query [{model}].
NotFoundHttpException, NotFoundException The requested resource was not found.
MethodNotAllowedHttpException, MethodNotAllowedException The HTTP method is not allowed for this resource.
TooManyRequestsHttpException, TooManyRequestsException Too many requests. Please try again later.
BadRequestHttpException, BadRequestException The request is invalid.
UnauthorizedHttpException, UnauthorizedException, AuthenticationException Authentication is required.
ForbiddenHttpException, ForbiddenException, AuthorizationException You are not authorized to perform this action.
PDOException A database operation failed.
InvalidArgumentException The provided input is invalid.
OutOfBoundsException The requested item was not found.
OutOfRangeException The requested value is out of range.
LengthException The provided value has an invalid length.
DomainException The provided value is not valid for this operation.
TypeError The operation received a value of an invalid type.
ParseError The request could not be processed.
UnexpectedValueException The operation returned an unexpected result.
DivisionByZeroError, ArithmeticError, RuntimeException, LogicException, ErrorException, Error, Exception The operation could not be completed.

Anything not matched falls back to step 7 of the priority order above.

πŸ“Š Logging to Kibana

1️⃣ Generate the middleware

php artisan make:errorhandler-middleware

Creates app/Http/Middleware/LogRequestResponse.php (use --force to regenerate).

2️⃣ Configure .env

APP_ENV=production
APP_DEBUG=false

ERROR_HANDLER_KIBANA=true
KIBANA_URL=https://your-elasticsearch:9200/error-handler/_doc
KIBANA_TIMEOUT=2
KIBANA_API_KEY=your-base64-api-key

…and wire them in config/error-handler.php (the generated file doesn't include kibana_timeout or kibana_headers yet, so add them):

'kibana_logging' => (bool) env('ERROR_HANDLER_KIBANA', false),
'kibana_url'     => env('KIBANA_URL', 'http://localhost:9200/error-handler/_doc'),
'kibana_timeout' => (int) env('KIBANA_TIMEOUT', 2),
'kibana_headers' => env('KIBANA_API_KEY')
    ? ['Authorization: ApiKey '.env('KIBANA_API_KEY')]
    : [],

Important

KIBANA_URL points to the Elasticsearch index endpoint (/<index>/_doc), not the Kibana UI. Kibana is where you view it: create a Data View for error-handler*.

3️⃣ Register the middleware

->withMiddleware(function (Middleware $middleware): void {
    $middleware->api(append: [\App\Http\Middleware\LogRequestResponse::class]);
})

4️⃣ Clear config & test

php artisan config:clear
curl -H "X-Correlation-ID: test-123" https://your-app.test/api/orders/999999

Search correlation_id : "test-123" in Kibana Discover.

Setup checklist

  • make:errorhandler-middleware generated
  • ERROR_HANDLER_KIBANA=true and KIBANA_URL set
  • API key / auth header set (if your cluster is secured)
  • Middleware registered on the api group
  • php artisan config:clear executed
  • Data view error-handler* created in Kibana
🧾 What is logged?

url, method, request_json, response_json, http_status, request_time (ms), correlation_id.

With kibana_logging off, the same payload goes to the Laravel log (Log::info). If sending to Kibana fails, the request still succeeds and a Request/response logging failed warning is written to the Laravel log.

[!WARNING] request_json is $request->all(): passwords, tokens and personal data are logged as-is. Redact sensitive fields in the generated middleware.

πŸ›  Troubleshooting

Environment must be development or production.

Map Laravel's env to the two allowed values in config/error-handler.php:

'environment' => in_array(env('APP_ENV'), ['local', 'development', 'testing'], true)
    ? 'development'
    : 'production',
Unauthenticated API request returns 500

Add AuthenticationException => 401 to the match in bootstrap/app.php, as shown in step 3 of Installation. Laravel does not convert it to an HTTP exception before render callbacks run.

The package's Http\* exceptions return 500

They expose getStatusCode() but don't implement Symfony's HttpExceptionInterface. Keep the BadRequestException => $exception->getStatusCode() arm in the match (all of them extend BusinessErrorHandler\Http\BadRequestException).

Nothing shows up in Kibana

Run php artisan config:clear, check storage/logs/laravel.log for Request/response logging failed, and verify that the URL ends with /_doc and the API key is valid.

correlation_id is null for successful requests

The middleware reads the X-Correlation-ID header from the response, and that header is only set on error responses. To keep the caller's ID on successful requests too, change this line in your generated LogRequestResponse.php:

'correlation_id' => $response->headers->get('X-Correlation-ID')
    ?? $request->header('X-Correlation-ID'),

Requests that succeed without an incoming X-Correlation-ID header still log null.

πŸ§ͺ Testing & contributing

composer install
vendor/bin/phpunit

Issues and pull requests are welcome. Please add or update tests in tests/ for any behavior change.

πŸ“„ License

MIT. See LICENSE.