Linus Larsson

Sending error messages from R to Slack

When you're working with scheduled R scripts, it could be useful to get an alert when something goes wrong. Of course, there are ways to send emails, but wouldn't it be nice if your entire team could get a notice in real time in Slack instead (or as a complement to emails)?

This is actually super easy to do. The first thing you need to do is to create your own Slack app. Head over to and click on "Create New App". Choose a name for the app and what workspace it will belong to, as shown in the image below.

Now head over to "Incoming Webhooks" and activate it. Once it's been activated, a new field should appear, where you can choose to create a new webhook. Click on that option and pick a channel or user that you want to send the messages to. When you're done it should look as the following.

That's all you have to do in Slack to get this to work, just make sure to copy the webhook URL. If you check the channel you picked, there should be a message saying that you made a new integration to it.

Now, let's head over to RStudio! The key is to put the code you want to run within tryCatch. When an error occur, a message will be sent to Slack, using the webhook you created before.

hook <- ""
title <- "Something went wrong when trying to update Google Search Console data to BigQuery"

}, error = function(err){
  body <- list(
    text = title, 
    attachments = list(
        color = "#f00",
        fields = list(
            value = as.character(err)
        footer = "<|Go to RStudio>"
  POST(hook, encode = "json", body = body)

Make sure you keep the structure in "body". This will format it the correct way, as the Slack API demands. If you want to play around with it, you can check what you can do at the Slack API Reference. From now on, every time an error occurs, you will receive the message immediatley in your Slack channel.


Leave a Reply

Your email address will not be published. Required fields are marked *


Cookie Settings

© Copyright - - 2018-2024