Backend Development
Laravel
Subjective
Sep 30, 2025
Explain Error handling in Laravel with code examples.
Detailed Explanation
Laravel provides comprehensive error handling:
**Exception Handler (app/Exceptions/Handler.php):**
class Handler extends ExceptionHandler {
public function register() {
$this->reportable(function (Throwable $e) {
if ($e instanceof CustomException) {
Log::error("Custom error: " . $e->getMessage());
}
});
}
public function render($request, Throwable $e) {
if ($e instanceof ModelNotFoundException) {
return response()->json(["error" => "Resource not found"], 404);
}
return parent::render($request, $e);
}
}
**Custom Exceptions:**
class CustomException extends Exception {
public function report() {
Log::error("Custom exception occurred");
}
public function render($request) {
return response()->view("errors.custom", [], 500);
}
}
**Try-Catch Blocks:**
public function processPayment($amount) {
try {
$payment = PaymentGateway::charge($amount);
return $payment;
} catch (PaymentException $e) {
Log::error("Payment failed: " . $e->getMessage());
throw new CustomException("Payment processing failed");
} catch (Exception $e) {
Log::error("Unexpected error: " . $e->getMessage());
throw $e;
}
}
**Error Views:**
Page Not Found
The requested page could not be found.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts