Skip to content

Instantly share code, notes, and snippets.

@sergeylukin
Created October 17, 2018 12:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergeylukin/600ac0533c4b4f4d40b5968e0753b22d to your computer and use it in GitHub Desktop.
Save sergeylukin/600ac0533c4b4f4d40b5968e0753b22d to your computer and use it in GitHub Desktop.
Send PHP fatal errors to Slack
<?php
register_shutdown_function("shutdown_error_handler");
function FriendlyErrorType($type)
{
switch($type)
{
case E_ERROR: // 1 //
return 'E_ERROR';
case E_WARNING: // 2 //
return 'E_WARNING';
case E_PARSE: // 4 //
return 'E_PARSE';
case E_NOTICE: // 8 //
return 'E_NOTICE';
case E_CORE_ERROR: // 16 //
return 'E_CORE_ERROR';
case E_CORE_WARNING: // 32 //
return 'E_CORE_WARNING';
case E_COMPILE_ERROR: // 64 //
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING: // 128 //
return 'E_COMPILE_WARNING';
case E_USER_ERROR: // 256 //
return 'E_USER_ERROR';
case E_USER_WARNING: // 512 //
return 'E_USER_WARNING';
case E_USER_NOTICE: // 1024 //
return 'E_USER_NOTICE';
case E_STRICT: // 2048 //
return 'E_STRICT';
case E_RECOVERABLE_ERROR: // 4096 //
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED: // 8192 //
return 'E_DEPRECATED';
case E_USER_DEPRECATED: // 16384 //
return 'E_USER_DEPRECATED';
}
return "";
}
function shutdown_error_handler() //will be called when php script ends.
{
$lasterror = error_get_last();
$type = $lasterror['type'];
$typeName = FriendlyErrorType($type);
$message = $lasterror['message'];
$file = $lasterror['file'];
$line = $lasterror['line'];
if(isset($lasterror) && in_array($typeName, ['E_ERROR', 'E_PARSE', 'E_COMPILE_ERROR', 'E_USER_ERROR']))
{
$payload = [
'text' => "
Error ({$typeName}) | PHP Stopped \n
File ({$file}:{$line}) \n
Message ({$message}) \n",
];
$ch = curl_init("<SLACK WEB HOOK URL>");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
$result = curl_exec($ch);
curl_close($ch);
if($result === false)
{
die('Curl error: ' . curl_error($ch));
}
}
}
<?php require __DIR . '/error_handler_slack.php';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment