Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Exceptions Laravel Package

laravel-json-api/exceptions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require laravel-json-api/exceptions
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="LaravelJsonApi\Exceptions\ExceptionsServiceProvider"
    
  2. Basic Usage Throw a JsonApiException to return standardized JSON:API error responses:

    use LaravelJsonApi\Exceptions\JsonApiException;
    
    throw new JsonApiException('Resource not found', 404, ['id' => '123']);
    

    This automatically formats the response as:

    {
      "errors": [
        {
          "status": "404",
          "title": "Resource not found",
          "detail": null,
          "source": {
            "pointer": "/data/123"
          }
        }
      ]
    }
    
  3. First Use Case Replace generic HttpException responses in controllers with JsonApiException for consistent API error formatting.


Implementation Patterns

Common Workflows

  1. Controller-Level Errors Replace abort(404) with:

    throw new JsonApiException('Not found', 404, ['id' => $request->route('id')]);
    
  2. Validation Errors Use JsonApiValidationException for form validation:

    use LaravelJsonApi\Exceptions\JsonApiValidationException;
    
    $validator = Validator::make($request->all(), ['email' => 'required|email']);
    if ($validator->fails()) {
        throw new JsonApiValidationException($validator);
    }
    
  3. Custom Error Types Extend JsonApiException for domain-specific errors:

    class PaymentFailedException extends JsonApiException
    {
        public function __construct($message, $paymentId)
        {
            parent::__construct($message, 402, ['id' => $paymentId]);
        }
    }
    
  4. Middleware Integration Catch exceptions in middleware to log or transform errors:

    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (JsonApiException $e) {
            // Custom logic (e.g., logging)
            return response()->json($e->toArray(), $e->getStatusCode());
        }
    }
    

Integration Tips

  • API Resources: Pair with laravel-json-api/v5 for consistent error responses alongside resource serialization.
  • Testing: Use JsonApiException in tests to assert error formats:
    $this->expectException(JsonApiException::class);
    $this->expectExceptionMessage('Not found');
    

Gotchas and Tips

Pitfalls

  1. Missing source Pointer If source data (e.g., id) is omitted, the error lacks context. Always include identifiers:

    // Bad: No pointer to locate the error.
    throw new JsonApiException('Invalid', 400);
    
    // Good: Includes `id` for debugging.
    throw new JsonApiException('Invalid', 400, ['id' => $userId]);
    
  2. Overriding Default Config The package uses config('jsonapi-exceptions') for defaults (e.g., include_stacktrace). Ensure your .env or config/jsonapi-exceptions.php doesn’t conflict:

    'include_stacktrace' => env('APP_DEBUG'), // Defaults to `false` in production.
    
  3. Nested Exceptions Avoid wrapping JsonApiException in other exceptions (e.g., Handler classes). Let the exception propagate directly.

Debugging

  • Stack Traces: Enable include_stacktrace in config for development:
    'include_stacktrace' => true,
    
  • Log Errors: Use Laravel’s logging to inspect exceptions:
    Log::error('JSON:API Error', ['exception' => $e]);
    

Extension Points

  1. Custom Error Formats Override toArray() in a subclass:

    class CustomException extends JsonApiException
    {
        public function toArray(): array
        {
            return [
                'errors' => [
                    [
                        'status' => $this->getStatusCode(),
                        'title' => $this->getMessage(),
                        'meta' => ['custom_field' => 'value'] // Add custom data
                    ]
                ]
            ];
        }
    }
    
  2. Global Exception Handler Use Laravel’s App\Exceptions\Handler to centralize error formatting:

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof JsonApiException) {
            return response()->json($exception->toArray(), $exception->getStatusCode());
        }
        return parent::render($request, $exception);
    }
    
  3. Localization Localize error messages via Laravel’s translation system:

    throw new JsonApiException(__('validation.required', ['attribute' => 'email']), 400);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus