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

Exceptions Laravel Package

dosfarma/exceptions

Lightweight Laravel/PHP exception utilities for standardizing, wrapping, and handling application errors. Helps you define consistent exception types and messages across your codebase, improving error clarity, debugging, and maintainability with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dosfarma/exceptions
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Dosfarma\Exceptions\ExceptionsServiceProvider::class,
    ],
    
  2. Basic Usage Define a custom exception:

    use Dosfarma\Exceptions\ApiException;
    
    class UserNotFoundException extends ApiException
    {
        public function __construct()
        {
            parent::__construct('User not found', 404);
        }
    }
    
  3. First Use Case Throw the exception in a controller:

    public function show($id)
    {
        $user = User::find($id);
        if (!$user) {
            throw new UserNotFoundException();
        }
        return $user;
    }
    

Implementation Patterns

Exception Handling Workflows

  1. Centralized Exception Handling Override App\Exceptions\Handler to format exceptions:

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof \Dosfarma\Exceptions\ApiException) {
            return response()->json([
                'error' => $exception->getMessage(),
                'code' => $exception->getCode(),
            ], $exception->getCode());
        }
        return parent::render($request, $exception);
    }
    
  2. Structured Error Responses Extend ApiException for consistent payloads:

    class ValidationException extends ApiException
    {
        public function __construct(array $errors)
        {
            parent::__construct('Validation failed', 422, [
                'errors' => $errors,
            ]);
        }
    }
    
  3. Middleware Integration Use middleware to log exceptions:

    namespace App\Http\Middleware;
    
    use Dosfarma\Exceptions\ApiException;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    class LogExceptions
    {
        public function handle(Request $request, Closure $next)
        {
            try {
                return $next($request);
            } catch (ApiException $e) {
                \Log::error($e->getMessage(), ['exception' => $e]);
                throw $e;
            }
        }
    }
    
  4. API Resource Integration Return exceptions as JSON responses:

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return response()->json(null, 204);
    }
    

Gotchas and Tips

Pitfalls

  1. Inconsistent HTTP Codes Ensure all custom exceptions extend ApiException and define proper HTTP status codes (e.g., 404, 400, 500).

  2. Overriding Default Behavior If extending App\Exceptions\Handler, ensure the render method doesn’t swallow ApiException instances unintentionally.

  3. Missing Error Details in Production Avoid exposing sensitive data in exception messages or payloads. Use environment checks:

    if (app()->environment('local')) {
        return response()->json(['error' => $exception->getMessage()], 500);
    }
    

Debugging

  1. Log Unhandled Exceptions Add a fallback in App\Exceptions\Handler:

    public function report(Throwable $exception)
    {
        if ($exception instanceof \Dosfarma\Exceptions\ApiException) {
            \Log::error('API Exception: ' . $exception->getMessage());
        }
    }
    
  2. Check Exception Payloads Use dd() to inspect exception data:

    try {
        // ...
    } catch (ApiException $e) {
        dd($e->getData()); // Inspect payload structure
    }
    

Extension Points

  1. Custom Exception Classes Extend ApiException for domain-specific errors:

    class PaymentFailedException extends ApiException
    {
        public function __construct(string $message, array $details = [])
        {
            parent::__construct($message, 402, $details);
        }
    }
    
  2. Dynamic Error Responses Use exception data to customize responses:

    public function render($request, PaymentFailedException $e)
    {
        return response()->json([
            'error' => $e->getMessage(),
            'details' => $e->getData(),
            'suggestions' => ['Retry payment', 'Contact support'],
        ], 402);
    }
    
  3. Localization Support Add language-specific messages:

    class UserNotFoundException extends ApiException
    {
        public function __construct()
        {
            $message = __('exceptions.user_not_found');
            parent::__construct($message, 404);
        }
    }
    
  4. Testing Exceptions Mock exceptions in tests:

    $this->expectException(UserNotFoundException::class);
    $this->expectExceptionCode(404);
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor