Uygulamanızda hataları nasıl yönetiyorsunuz? Laravel'in güçlü hata yönetim sistemiyle kullanıcı dostu deneyimler oluşturmayı öğrenelim!
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 }); }
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>
$this->renderable(function (ModelNotFoundException $e) { return response()->view('errors.404', [], 404); }); $this->renderable(function (AuthorizationException $e) { return response()->view('errors.403', [], 403); });
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() ]); }
// 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', ], ]
$this->renderable(function (ValidationException $e) { return response()->json([ 'status' => 'error', 'errors' => $e->errors(), 'documentation_url' => config('app.api_docs_url') ], 422); });
// 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);
composer require sentry/sentry-laravel
// .env SENTRY_LARAVEL_DSN=https://example@sentry.io/1
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); }
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
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 🚀