Step-by-Step Guide on How to Send Error Messages from Laravel App to Slack Using Webhooks
Published: 2024-01-08 07:37:20

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/paogzrlzs6927cyphlq3.png)

## 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](https://laravel.com/docs/10.x/installation#creating-a-laravel-project)  called slack-webhook.

```
composer create-project laravel/laravel slack-webhook
```

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

Head to [Slack documentation](https://slack.com/intl/en-gb/help/articles/206845317-Create-a-Slack-workspace#desktop-1) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d10ddrtbr4l6ovzf50yg.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wz0sbn9is3a5yqzvqti1.gif)

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


![Slack webhook config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zla3t59wivtxw2gid3ui.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfckw1fnbbf8wbytqjj3.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jch24afou76mooax3a4f.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2qvrberwf1k4o5do8zo.jpg)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w40f0tgnsulrmmhprh99.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eljll4tiaeteardxt0ow.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nso7mu6uc5xzyq4ap2f4.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/toss4sd9uyao57vqxcof.png)

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,
],
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pob6pmj6j30i18whqnx.jpeg)

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');
});
```


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(),
          ]);
      });
  }
```


Start the application by executing the command below.

```
php artisan serve
```

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


![http 500 error page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sl3di565cj9kmts8mrma.png)

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


![Slack output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fvnrblzyttol2dh7752.png)

## 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.