DEV Community

Cover image for Step-by-Step Guide on How to Send Error Messages from Laravel App to Slack Using Webhooks
Michael Menebraye
Michael Menebraye

Posted on • Updated on

Step-by-Step Guide on How to Send Error Messages from Laravel App to Slack Using Webhooks

Error messages serve a vital role in web development by identifying and addressing issues within an application. Developers rely on these messages for valuable information that facilitates debugging and troubleshooting. Typically containing details about the nature and location of errors, these messages help developers quickly pinpoint and resolve issues. Their significance spans across development, testing, and production phases, contributing to a smoother and more efficient development cycle.

Importance of HTTP Error Messages in Web Development:

Issue Identification: Error messages play a vital role in pinpointing problems within code, including syntax errors, runtime issues, and logical errors.

Debugging Support: The information provided in error messages aids developers in debugging, helping them trace and resolve the root cause of the problem.

Security Considerations: Careful management of error messages is crucial to avoid exposing sensitive information, making generic messages preferable in a production environment.

Logging and Monitoring: Error messages are logged for further analysis, enabling monitoring tools to track application health and performance.

By comprehensively addressing error messages, developers enhance the reliability, security, and overall quality of web applications.

Webhook

Webhooks are automated messages sent from one application to another when specific events occur. They have a message, or payload, and are sent to a unique URL. This allows apps to push data to each other and not waste time checking and waiting. Similarly, Slack employs user-defined HTTP callbacks, known as Webhooks, to notify your Slack application about events from external services like Laravel in real-time. In essence, the webhook URL acts as a channel, transmitting messages from your Laravel app to your Slack channel seamlessly.

slack webhook diagram

What is the purpose of forwarding error messages from your Laravel applications to your Slack workspace?

Imagine being a member of a team that is building a large Laravel application. Upon completing the project, the Laravel app was deployed to the production environment; deliberately setting the APP_DEBUG configuration in your environment file to false. This deliberate choice means that only a standard HTTP 500 server error message is shown instead of detailed error messages when issues arise. In this scenario, if users face problems while using the Laravel app in the production environment, the development team is unaware of these errors and when a user reports the issue, the development team may find it challenging to pinpoint the exact cause of the problem since they lack information about the specific error. To address this challenge, a Slack webhook can be employed to instantly notify the development team of errors as they occur, providing real-time insights into the exact error message and facilitating prompt resolution.

Prerequisites

  • Laravel and PHP Basics
  • Composer and PHP installed
  • Slack workspace

Now that you have a fundamental understanding of webhooks and understand the benefits of integrating Slack webhooks in Laravel applications, the next step is to delve deeper by integrating Slack webhooks into the application. To begin, we need to:

  1. Create a new Laravel application.

  2. Set up a Slack account and configure the Slack webhook.

  3. Integrate the Slack webhook into your Laravel application.

Step 1: Create a new Laravel application.

Go to your terminal or command prompt and paste the following command to create a new Laravel app called slack-webhook.

composer create-project laravel/laravel slack-webhook
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up a Slack account and configure the Slack webhook.

Head to Slack documentation to create a new workspace if you don't have one. After setting up your slack workspace, click on the Add channel button on the left-side navigation to create a new channel that will receive error messages. For this tutorial, assign the name laravel-error-message.

Slack channel

With your channel successfully created, let's move on to configuring the Slack webhook. Click the dropdown menu next to your Slack workspace name at the top of the left-side navigation on your screen. Subsequently, select Tools & settings and proceed to click on the Manage app button. This will redirect you to a new page.

Slack webhook config

Proceed to click on Build located on the right side of the top navigation bar.

Slack webhook config

Following that, click on the Create An App button. This action will prompt a modal pop-up card to appear. On the modal pop-up card, select the From Scratch option.

Slack webhook config

Proceed to enter a name in the App Name input field, and then select your Slack workspace name from the dropdown menu below.

Slack webhook config

Next, Activate your Slack webhook by:

  1. Navigating to Incoming Webhooks on the left-side navigation
  2. Toggle the Activate Incoming Webhook switch to enable it.

Slack webhook config

Once your webhook has been activated, scroll down the page and choose Add a New Webhook to Workspace. This will redirect you to a new page where you can select a channel.

Slack webhook config

Finally, choose the laravel-error-message channel created earlier. Click the Allow button to provide permission for sending messages to the Slack channel.

Slack webhook config

We have successfully generated our Slack webhook URL. Scroll to the bottom of the webpage to find the Slack webhook we generated. If you have cURL installed on your local machine, you can test the webhook by copying the Sample curl request to post to a channel URL and executing it in your terminal. Afterward, check your Slack channel; you will receive a "hello world" message. Please note that we will not be using the Sample curl request to post to a channel URL in our Laravel app.

Slack webhook config

Step 3: Integrate the Slack webhook into your Laravel application.

In this article, we'll utilize Slack incoming webhooks to post messages from our Laravel application by sending JSON payloads to our Slack channel. We'll be implementing the error message scenario mentioned earlier in our application. Here is a process flow diagram illustrating how the application will function.

Slack webhook process flow diagram

Start by launching the Laravel application created previously using your chosen code editor. Then, proceed to the config directory and open the logging.php file. Inside the logging.php file, find the slack driver, and copy the LOG_SLACK_WEBHOOK_URL.

'slack' => [
  'driver' => 'slack',
  'url' => env('LOG_SLACK_WEBHOOK_URL'),
  'username' => 'Laravel Log',
  'emoji' => ':boom:',
  'level' => env('LOG_LEVEL', 'critical'),
  'replace_placeholders' => true,
],
Enter fullscreen mode Exit fullscreen mode

The above configurations help tailor how Laravel logs messages to the Slack channel, defining details such as where to send the logs, how to format them, and under what conditions they should be logged.

Now, locate the .env file and follow these steps:

  • paste the LOG_SLACK_WEBHOOK_URL

  • Copy the webhook URL generated in the Slack configuration and assign it to 'LOG_SLACK_WEBHOOK_URL.

  • scroll to the top of the .env file and configure APP_DEBUG=false.

SLACK WEBHOOK URL

Open the web.php file in the routes directory and enhance the default route by incorporating an exception.

Route::get('/', function () {
  throw new Exception("Error Processing Request", 1);
  return view('welcome');
});
Enter fullscreen mode Exit fullscreen mode

Navigate to the Handler.php file in the app/Exceptions directory and revise the register method with the provided code. The following code retrieves the details of the error messages that will be sent to Slack.

<?php

use Illuminate\Support\Facades\Log;

public function register(): void
  {
      $this->reportable(function (Throwable $e) {
          Log::channel('slack')->error($e->getMessage(),[
              'file' => $e->getFile(),
              'Line' => $e->getLine(),
              'code' => $e->getCode(),
          ]);
      });
  }
Enter fullscreen mode Exit fullscreen mode

Start the application by executing the command below.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Go to your home page and refresh; you should encounter a 500 server error.

http 500 error page

Finally, check your Slack channel to view the error message sent from your Laravel application.

Slack output

Conclusion

Congratulations on successfully completing this step-by-step guide. At this point, you have acquired essential knowledge about the significance of implementing this process in your Laravel application. Feel free to leave a comment in the section below, and also share your thoughts on whether I should create similar tutorials or enhance this article.

Top comments (4)

Collapse
 
emmysteven profile image
Emmy Steven

This is an excellent post for the PHP and Laravel community, I love the way you took your time to be thorough and really detailed.

Pls keep it up, it can only get better.

Collapse
 
hummingbed profile image
Michael Menebraye

Thanks Emmy. Really apprecaite the feedback. will be dropping more contents like this.

Collapse
 
msassa profile image
Mauro Sassaroli

Hi Michael,

I've successfully implemented the notification system you recommended, and it's working wonderfully. However, I've encountered an issue where if the same error occurs repeatedly—say 500 times—it triggers 500 individual Slack notifications. Is there a way to limit the number of notifications sent for the same error? I'd like to set a threshold to avoid this overflow.

Thanks for your help!

Collapse
 
stanliwise profile image
stanliwise

Amazing content