Sending Message Error To Webhook Slack

Photo by Grace To on Unsplash

Register Webhook in Slack

Author
Author
{
"attachments": [
{
"color": "#f2c744",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*username:* \n Fred \n *error_code:* \n 500 \n *line_code:* \n 100 \n *function:* \n getHelp \n *Version*: \n 2.2.24"
}
}
]
}
]
}
Author

Setup in App

In my case using MVVM pattern, some code that will be displayed is ViewModel and Model . use pod alamofire for hit API

  • ViewModel (Function for hit Api to webhook slack)
func getReportErrorToSlack(error: String, lineStr: Int, functionStr: String) {let baseWebHook = "https://hooks.slack.com/services/xxxxxx/xxxxxx/xxxxxxx"var blocks = [[String: Any]]()var attacments = [[String: Any]]()let block = MyAppModel.Block(username: "user test", errorCode: "404", message: error, line: lineStr, function: functionStr)blocks.append(block.parameters!)let attacment = MyAppModel.Attachment(blocks: blocks)attacments.append(attacment.parameters!)let parameters = MyAppModel.Request(attachments: attacments)
Alamofire.request(baseWebHook, method: .post, parameters: parameters.parameters, encoding: JSONEncoding.default).responseJSON { response inprint(response) }}// How to useself.getReportErrorToSlack(error: error.localizedDescription, lineStr: #line, functionStr: #function)
  • Model Request

public struct MyAppModel {

public struct Request {
let attachments: [[String: Any]]

var parameters: [String: Any]? {
return [
"attachments": attachments
]
}
}

public struct Attachment {
let blocks: [[String: Any]]

func parameters() -> [String: Any] {
return [
"color": "#f2c744",
"blocks": blocks
]
}

}

public struct Block {

var username: String
var errorCode: String
var message: String
var line: Int
var function: String

var parameters: [String: Any]? {
return [
"type": "section",
"text": [
"type": "mrkdwn",
"text": "*username:* \n \(username) \n *error_code:* \n \(errorCode) \n *message_error:* \n \(message) \n *line_code:* \n \(line) \n *function:* \n \(function)"
]
]
}

}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store