design

Laravel'de Error Handling: Profesyonel Hata Yönetimi Rehberi

April 4, 2025


Uygulamanızda hataları nasıl yönetiyorsunuz? Laravel'in güçlü hata yönetim sistemiyle kullanıcı dostu deneyimler oluşturmayı öğrenelim!


1. Laravel Hata Yönetim Sistemi 🔍

Laravel'in hata yönetimi için Handler.php merkezi bir rol oynar:

// app/Exceptions/Handler.php
public function register()
{
    $this->reportable(function (Throwable $e) {
        // Hataları raporlama
    });

    $this->renderable(function (Throwable $e) {
        // Hataları görüntüleme
    });
}


2. Özel Hata Sayfaları 🎨

Blade Template ile Özelleştirme

php artisan make:view errors/404 --extends=layouts.app
php artisan make:view errors/500 --extends=layouts.app


404.blade.php Örneği:

<div class="error-container">
    <h1>404 | Sayfa Bulunamadı</h1>
    <p>Üzgünüz, aradığınız sayfa mevcut değil.</p>
    <a href="{{ url('/') }}" class="btn">Ana Sayfaya Dön</a>
    @include('partials.search-form')
</div>



HTTP Hata Kodlarına Özel Davranış

$this->renderable(function (ModelNotFoundException $e) {
    return response()->view('errors.404', [], 404);
});

$this->renderable(function (AuthorizationException $e) {
    return response()->view('errors.403', [], 403);
});


3. Akıllı Loglama Stratejileri 📊

Context ile Zenginleştirilmiş Loglar

try {
    // İş mantığı
} catch (Exception $e) {
    Log::channel('critical')->error('Ödeme hatası', [
        'user_id' => auth()->id(),
        'ip' => request()->ip(),
        'input' => request()->except(['password']),
        'error' => $e->getTraceAsString()
    ]);
}


Log Kanalları Yapılandırması

// config/logging.php
'channels' => [
    'payment_errors' => [
        'driver' => 'daily',
        'path' => storage_path('logs/payments.log'),
        'level' => 'error',
        'days' => 30,
    ],
    
    'security' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'level' => 'critical',
    ],
]


4. API Hata Yönetimi 🌐

Standart JSON Yanıtları

$this->renderable(function (ValidationException $e) {
    return response()->json([
        'status' => 'error',
        'errors' => $e->errors(),
        'documentation_url' => config('app.api_docs_url')
    ], 422);
});


Özel Exception Sınıfları

// app/Exceptions/ApiException.php
class ApiException extends Exception
{
    public function render($request)
    {
        return response()->json([
            'error' => class_basename($this),
            'message' => $this->getMessage(),
            'code' => $this->getCode()
        ], $this->getCode());
    }
}

// Kullanım
throw new ApiException('Geçersiz token', 401);


5. Hata İzleme Araçları 🛠️

Sentry Entegrasyonu

composer require sentry/sentry-laravel


// .env
SENTRY_LARAVEL_DSN=https://example@sentry.io/1


Özel Raporlama Mantığı

public function report(Throwable $exception)
{
    if ($this->shouldReport($exception)) {
        if (app()->environment('production')) {
            Sentry\captureException($exception);
        }
        
        if ($exception instanceof PaymentException) {
            Notification::route('slack', config('logging.channels.slack.url'))
                ->notify(new CriticalErrorNotification($exception));
        }
    }

    parent::report($exception);
}


6. Hata Sayfaları için SEO 🔎

error.blade.php Layout:

@section('seo')
    <meta name="robots" content="noindex">
    <title>@yield('error_title', 'Hata Oluştu') | {{ config('app.name') }}</title>
    <meta property="og:title" content="@yield('error_title')">
    <meta name="description" content="@yield('error_description')">
@endsection



Sonuç: Profesyonel Hata Yönetimi 🏆

  • %60 daha az kullanıcı kaybı 📉
  • %40 daha hızlı hata çözümü ⚡
  • Daha güvenli uygulama ortamı 🔒
Hata yönetimi için hangi stratejileri kullanıyorsunuz? Deneyimlerinizi yorumlarda paylaşın! 💬
Bir sonraki yazımız: 🚀 [Laravel'de Dependency Injection ve Service Container] - Laravel'in kalbindeki güç!

#Laravel #ErrorHandling #WebDevelopment #BestPractices #PHP 🚀

8 + 4 =