Advanced Error Handling and Logging in Laravel

Photo by Brett Jordan on Unsplash

Advanced Error Handling and Logging in Laravel

Laravel Oct 17, 2022

Errors and exceptions are an inevitable part of any software development process. They can occur due to various reasons such as bugs in the code, misconfigurations, or unexpected user input. In Laravel, a PHP web application framework, handling and logging errors and exceptions is a crucial aspect of maintaining the stability and reliability of the application. In this article, we will discuss advanced techniques for handling and logging errors and exceptions in Laravel.

Handling Errors

In Laravel, errors can be handled by creating custom error handlers. These custom error handlers can be created by implementing the Illuminate\Contracts\Debug\ExceptionHandler interface. Once the custom error handler is created, it can be registered in the app/Exceptions/Handler.php file.

Here is an example of a custom error handler that sends an email to the administrator when an error occurs:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Facades\Mail;

class CustomErrorHandler implements ExceptionHandler
{
    public function report(Exception $e)
    {
        Mail::to(config('app.admin_email'))->send(new ErrorOccured($e));
    }

    public function render($request, Exception $e)
    {
        return response()->view('errors.custom', ['exception' => $e], 500);
    }

    public function renderForConsole($output, Exception $e)
    {
        return $output->writeln(get_class($e).': '.$e->getMessage());
    }
}

In the above example, the report method sends an email to the administrator when an error occurs. The render method returns a custom view for displaying the error to the user, and the renderForConsole method returns the error message when the error occurs in the console.

Handling Exceptions

In Laravel, exceptions can be handled by creating custom exception handlers. These custom exception handlers can be created by extending the Illuminate\Foundation\Exceptions\Handler class. Once the custom exception handler is created, it can be registered in the app/Exceptions/Handler.php file.

Here is an example of a custom exception handler that sends an email to the administrator when an exception occurs:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Mail;

class CustomExceptionHandler extends ExceptionHandler
{
    public function report(Exception $e)
    {
        Mail::to(config('app.admin_email'))->send(new ExceptionOccured($e));
    }

    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

In the above example, the report method sends an email to the administrator when an exception occurs. The render method returns the default view for displaying the exception to the user, but you can also customize it to return your own view.

Logging Errors and Exceptions

In Laravel, errors and exceptions can be logged by using the built-in logging functionality. By default, Laravel logs errors and exceptions to the storage/logs directory. However, you can configure Laravel to log errors and exceptions to a different directory or to a remote service such as Papertrail by updating the config/logging.php file.

Here is an example of how to configure Laravel to log errors and exceptions to a remote service such as Papertrail:

'papertrail' => [
    'driver' => 'monolog',
    'level' => 'debug',
    'handler' => SyslogUdpHandler::class,
    'handler_with' => [
        'host' => env('PAPERTRAIL_URL'),
        'port' => env('PAPERTRAIL_PORT'),
    ],
],

In the above example, the 'papertrail' channel is being used to log errors and exceptions to a remote service using the SyslogUdpHandler. The 'host' and 'port' options are set to the values provided by the Papertrail service.

You can also customize the log levels and channels to suit your needs. For example, you can configure Laravel to log only critical errors to the papertrail channel and log all errors to the daily log channel, like this:

'papertrail' => [
    'driver' => 'monolog',
    'level' => 'critical',
    'handler' => SyslogUdpHandler::class,
    'handler_with' => [
        'host' => env('PAPERTRAIL_URL'),
        'port' => env('PAPERTRAIL_PORT'),
    ],
],

'daily' => [
    'driver' => 'daily',
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
    'days' => 14,
],

In this example, the papertrail channel is set to log only critical errors, while the daily channel is set to log all errors with a level of "debug" and above.

Conclusion

In this article, we have discussed advanced techniques for handling and logging errors and exceptions in Laravel. We have seen how to create custom error and exception handlers and how to configure Laravel to log errors and exceptions to a remote service such as Papertrail. By implementing these techniques, you can ensure that your Laravel application is stable and reliable, and that any errors or exceptions that occur are handled and logged in a way that is suitable for your needs.

Tags

Anurag Deep

Logical by Mind, Creative by Heart