PHPackages                             jeromejhipolito/laravel-global-error-formatter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. jeromejhipolito/laravel-global-error-formatter

ActiveLibrary[API Development](/categories/api)

jeromejhipolito/laravel-global-error-formatter
==============================================

Global error/exception handler for Laravel APIs. Standardized JSON error responses with configurable exception mappings.

v1.0.0(3mo ago)111MITPHPPHP ^8.2

Since Feb 2Pushed 3mo agoCompare

[ Source](https://github.com/jeromejhipolito/laravel-global-error-formatter)[ Packagist](https://packagist.org/packages/jeromejhipolito/laravel-global-error-formatter)[ RSS](/packages/jeromejhipolito-laravel-global-error-formatter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (2)Used By (0)

Laravel Global Error Formatter
==============================

[](#laravel-global-error-formatter)

Global error/exception handler for Laravel APIs. Provides standardized JSON error responses with configurable exception mappings.

Features
--------

[](#features)

- Global exception handling for all API errors
- Consistent JSON error response format
- Configurable exception mappings (add your own exceptions)
- Built-in handling for common Laravel exceptions
- Customizable response structure
- First-error or all-errors validation format
- Environment-based debug info (trace &amp; error details)
- Translation support for error messages
- Base FormRequest class for consistent validation errors

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11.0+ or 12.0+

Installation
------------

[](#installation)

```
composer require jeromejhipolito/laravel-global-error-formatter
```

The package will auto-register its service provider.

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag=global-error-formatter-config
```

Quick Start
-----------

[](#quick-start)

### Register in bootstrap/app.php

[](#register-in-bootstrapappphp)

```
use JeromeJHipolito\GlobalErrorFormatter\GlobalErrorFormatter;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        GlobalErrorFormatter::register($exceptions);
    })
    ->create();
```

That's it! All exceptions in API requests will now return consistent JSON responses.

Response Format
---------------

[](#response-format)

```
{
    "status": "error",
    "message": "Resource not found.",
    "errors": null,
    "trace": null
}
```

Environment-Based Error Details
-------------------------------

[](#environment-based-error-details)

The package automatically shows/hides error details based on your environment:

```
// config/global-error-formatter.php

// Stack trace - only shown in debug mode
'include_trace' => env('GLOBAL_ERROR_INCLUDE_TRACE', env('APP_DEBUG', false)),

// Error details (exception message) - only shown in debug mode
'include_error_details' => env('GLOBAL_ERROR_DETAILS', env('APP_DEBUG', false)),
```

**Development (APP\_DEBUG=true):**

```
{
    "status": "error",
    "message": "Something went wrong.",
    "errors": "SQLSTATE[42S02]: Base table or view not found...",
    "trace": [...]
}
```

**Production (APP\_DEBUG=false):**

```
{
    "status": "error",
    "message": "Something went wrong."
}
```

Adding Custom Exceptions
------------------------

[](#adding-custom-exceptions)

### Via Configuration

[](#via-configuration)

```
// config/global-error-formatter.php
'exceptions' => [
    \App\Exceptions\PaymentException::class => [
        'status' => 402,
        'message' => 'Payment required.',
    ],
    \App\Exceptions\CouponException::class => [
        'status' => 400,
        'message' => null,  // Uses exception's getMessage()
    ],
],
```

### Programmatically

[](#programmatically)

```
use JeromeJHipolito\GlobalErrorFormatter\GlobalErrorFormatter;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        $formatter = app(GlobalErrorFormatter::class);

        $formatter
            ->addException(PaymentException::class, 402, 'Payment required.')
            ->addException(CouponException::class, 400);  // Uses exception message

        $exceptions->render(function (Throwable $e, Request $request) use ($formatter) {
            if ($request->expectsJson()) {
                return $formatter->format($e);
            }
            return null;
        });
    })
    ->create();
```

Built-in Exception Handling
---------------------------

[](#built-in-exception-handling)

ExceptionStatusDefault Message`ModelNotFoundException`404Resource not found.`NotFoundHttpException`404Route not found.`AuthenticationException`401Unauthenticated.`AuthorizationException`403Unauthorized.`ValidationException`422First validation error`ThrottleRequestsException`429Too many requests.Other exceptions500Something went wrong.Using BaseFormRequest
---------------------

[](#using-baseformrequest)

Extend `BaseFormRequest` for consistent validation error responses:

```
use JeromeJHipolito\GlobalErrorFormatter\BaseFormRequest;

class CreateUserRequest extends BaseFormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8',
        ];
    }
}
```

Validation errors will automatically use the configured format.

Configuration Options
---------------------

[](#configuration-options)

### Response Keys

[](#response-keys)

Customize the JSON response structure:

```
'response_keys' => [
    'status' => 'status',      // Change to 'result', 'success', etc.
    'message' => 'message',    // Change to 'msg', 'error', etc.
    'errors' => 'errors',      // Change to 'details', 'data', etc.
    'trace' => 'trace',        // Change to 'stack', 'debug', etc.
],
```

### Status Values

[](#status-values)

Customize the status field values:

```
'status_values' => [
    'success' => 'success',
    'error' => 'error',        // Change to 'failed', 'failure', etc.
],
```

### Validation Format

[](#validation-format)

Choose how validation errors are returned:

```
// 'first' - Only the first error message (default)
'validation_format' => 'first',

// 'all' - All errors with field names
'validation_format' => 'all',
```

**First format response:**

```
{
    "status": "error",
    "message": "The email field is required."
}
```

**All format response:**

```
{
    "status": "error",
    "message": "Validation failed.",
    "errors": {
        "email": ["The email field is required."],
        "password": ["The password must be at least 8 characters."]
    }
}
```

### Translation Support

[](#translation-support)

```
// Pass messages through trans() helper
'translate_messages' => true,
```

This allows you to create translation files for error messages:

```
// lang/ja/messages.php
return [
    'Resource not found.' => 'リソースが見つかりません。',
    'Validation failed.' => '検証に失敗しました。',
];
```

Conditional Registration
------------------------

[](#conditional-registration)

Only handle specific requests:

```
GlobalErrorFormatter::register($exceptions, function (Throwable $e, Request $request) {
    // Only handle API routes
    return $request->is('api/*');
});
```

Override Default Messages
-------------------------

[](#override-default-messages)

```
'defaults' => [
    'model_not_found' => [
        'status' => 404,
        'message' => 'The requested item was not found.',
    ],
    'authentication' => [
        'status' => 401,
        'message' => 'Please log in to continue.',
    ],
    // ... other defaults
],
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Credits
-------

[](#credits)

- [Jerome Hipolito](https://github.com/jeromejhipolito)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance81

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

100d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0306a31e9423235a83c0093c7caaa9725e76e8796396ed3bc51225dd0cdaa4f1?d=identicon)[jeromejhipolito](/maintainers/jeromejhipolito)

---

Tags

responsejsonformatterapilaravelexceptionerrorhandlerglobal

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/jeromejhipolito-laravel-global-error-formatter/health.svg)

```
[![Health](https://phpackages.com/badges/jeromejhipolito-laravel-global-error-formatter/health.svg)](https://phpackages.com/packages/jeromejhipolito-laravel-global-error-formatter)
```

###  Alternatives

[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[obiefy/api-response

Simple Laravel package to return Json responses.

17324.6k](/packages/obiefy-api-response)[djurovicigoor/larajsonresponse

Laravel API wrapper for returning JSON response.

116.8k](/packages/djurovicigoor-larajsonresponse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
