Weave Code
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

Error Response Bundle Laravel Package

bugloos/error-response-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bugloos/error-response-bundle
    

    Register the bundle in config/bundles.php (Symfony-only):

    return [
        // ...
        Bugloos\ErrorResponseBundle\BugloosErrorResponseBundle::class => ['all' => true],
    ];
    
  2. Basic Usage: Trigger an error response in a controller:

    use Bugloos\ErrorResponseBundle\Exception\ErrorResponseException;
    
    public function exampleAction()
    {
        throw new ErrorResponseException('Something went wrong', 400);
    }
    

    The response will automatically format as JSON with a standardized structure:

    {
        "success": false,
        "message": "Something went wrong",
        "errors": [],
        "data": null,
        "status": 400
    }
    
  3. First Use Case: Replace generic JsonResponse or HttpException in APIs for consistent error formatting. Example:

    try {
        $user = User::findOrFail($id);
    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
        throw new ErrorResponseException('User not found', 404);
    }
    

Implementation Patterns

Standardized Error Responses

Workflow:

  1. Centralized Error Handling: Override app/Exceptions/Handler.php to convert exceptions to ErrorResponseException:

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
            return new ErrorResponseException($exception->getMessage(), $exception->getStatusCode());
        }
        return parent::render($request, $exception);
    }
    
  2. Structured Error Data: Pass arrays for errors or data fields:

    throw new ErrorResponseException('Validation failed', 422, [
        'errors' => ['email' => ['The email is invalid.']],
        'data' => ['input' => $request->all()]
    ]);
    
  3. Validation Errors: Integrate with Laravel’s validator:

    $validator = Validator::make($request->all(), ['email' => 'required|email']);
    if ($validator->fails()) {
        throw new ErrorResponseException('Validation failed', 422, [
            'errors' => $validator->errors()->toArray()
        ]);
    }
    

API Integration

Patterns:

  • API Resources: Extend ErrorResponseException for custom responses:
    throw new ErrorResponseException('Unauthorized', 401, [], [
        'auth' => ['token' => 'required']
    ]);
    
  • Middleware: Use to wrap API routes:
    public function handle($request, Closure $next)
    {
        try {
            return $next($request);
        } catch (ErrorResponseException $e) {
            return response()->json($e->getResponseData(), $e->getStatusCode());
        }
    }
    

Testing

Mock Responses:

$exception = new ErrorResponseException('Test error', 500);
$this->expectException(\Bugloos\ErrorResponseBundle\Exception\ErrorResponseException::class);
$this->expectExceptionMessage('Test error');

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel:

    • The bundle is Symfony-first. In Laravel, manually register the exception handler in app/Exceptions/Handler.php or use middleware.
    • Fix: Override render() as shown above.
  2. Response Overrides:

    • Default response structure may conflict with existing JSON responses. Ensure no duplicate success/status fields in your app.
    • Tip: Use ->merge() to combine custom data:
      $response = $exception->getResponseData();
      $response['meta'] = ['timestamp' => now()];
      
  3. Validation Edge Cases:

    • Nested validator errors may not serialize cleanly. Flatten arrays explicitly:
      'errors' => array_merge(...$validator->errors()->toArray())
      

Debugging

  1. Missing Responses:

    • Verify the exception is caught by ErrorResponseException or its handler. Check Symfony’s ProblemDetails middleware if using Symfony components.
  2. Status Code Conflicts:

    • Laravel’s HttpException may override status codes. Explicitly set:
      throw new ErrorResponseException('Error', 500, [], [], 500);
      

Extension Points

  1. Custom Response Classes: Extend ErrorResponseException for domain-specific errors:

    class PaymentErrorException extends ErrorResponseException {
        public function __construct(string $message, array $paymentData = []) {
            parent::__construct($message, 402, [], ['payment' => $paymentData]);
        }
    }
    
  2. Dynamic Fields: Add computed fields to responses:

    $exception->setResponseData('debug', app()->environment('local'));
    
  3. Localization: Override getMessage() to support translations:

    throw new ErrorResponseException(__('errors.user.not_found'), 404);
    

Configuration Quirks

  • No Config File: The bundle relies on runtime overrides. For global defaults, extend the exception class or use middleware.
  • Symfony ProblemDetails: If using Symfony’s ProblemDetails, disable it to avoid conflicts:
    # config/packages/framework.yaml
    framework:
        http_client:
            problem_details: false
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui