Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Laravel Error Handling
Laravel Advanced FREE

Error Handling

Lesson 2 of 17 Advanced Interactive

Error handling in app/Exceptions/Handler.php.

Logging

Log::info(), Log::error() � logs to storage/logs/.

Custom Exceptions

Create custom exceptions and render in handler.

Syntax

LARAVEL
Log::info("User logged in", ["user_id" => $user->id]);
Log::error("Payment failed", ["order_id" => $order->id]);

class PaymentException extends \Exception {}

// In handler
public function register() {
    $this->renderable(function (PaymentException $e, $request) {
        return response()->json(["error" => $e->getMessage()], 422);
    });
}

Example

LARAVEL
try {
    $payment = Stripe::charges()->create([...]);
} catch (CardException $e) {
    Log::error("Payment declined", ["user" => auth()->id()]);
    return back()->withErrors(["payment" => "Card declined"]);
}

Output

Payment declined. Please try another card.

Try It Yourself

Editor Settings

Output Error Success

Click Run to see output

Console
Ctrl + Enter Run | Tab Indent | Esc Exit fullscreen

Reset Code?

Your changes will be replaced with the original example code.

Practice

1
Exercise

Create and log a custom exception.

Answer
class OrderNotFoundException extends \Exception {}
try {
    throw new OrderNotFoundException("Order #999 not found");
} catch (OrderNotFoundException $e) {
    Log::error($e->getMessage());
}

Quick Quiz

1

Where are Laravel logs stored?

Logs are in storage/logs/.

Interview Questions

Use model binding for automatic 404, or abort(404). Custom pages in resources/views/errors/404.blade.php.