laravel Junior

How to handle exceptions in Laravel?

Short Answer

Laravel uses exception handling via the bootstrap/app.php handler. Exceptions are caught globally and rendered as responses or logged.

Detailed Answer

Laravel\'s exception handling: 1. The app handler catches all uncaught exceptions 2. Exceptions are rendered as HTTP responses (404, 403, 422, 500) 3. Custom exception pages in resources/views/errors/ 4. report() method for logging 5. render() method for response generation Best practices: - Use try-catch for expected failures (payment, API calls) - Create custom exception classes for domain errors - Use abort() for early exits with specific status codes - Handle validation exceptions gracefully - Log unexpected exceptions for debugging

Code Example

Example
<?php
// Custom exception
class PaymentFailedException extends \RuntimeException
{
    public function __construct(
        string $message = 'Payment processing failed',
        int $code = 422,
        ?\Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);
    }
}

// Usage in service
public function processPayment(Payment $payment): void
{
    try {
        $this->gateway->charge($payment);
    } catch (\Exception $e) {
        Log::error('Payment failed', ['error' => $e->getMessage()]);
        throw new PaymentFailedException($e->getMessage(), 422, $e);
    }
}

// Handler
public function register(): void
{
    $this->reportable(function (PaymentFailedException $e) {
        // Custom reporting logic
    });
}

// Custom error page
// resources/views/errors/422.blade.php

Interview Tip

Discuss the difference between report() (logging) and render() (response). Mention custom exception pages and the abort() helper.