在实际的开发过程当中或者项目已经上线了,但有时候总会碰到一些莫名其妙的报错问题。这时候如果能让程序报错的详细信息及报错位置及时通知到开发人员,便能很快定位和解决问题了。及时推送异常信息最简单的实现方式之一,就是使用钉钉群进行自定义机器人进行通知。
首先在钉钉里要把相关的人员拉到一个群里,然后取一个响亮亮的名字。再点击右上角的三个点>智能群助手>添加机器人>自定义机器人。如下图所示:
给你的机器人也起个响亮亮的名字,点击完成。
把下图中的Webhook的地址复制保存下来。
php+tp6 这里会用到一个框架里的应用异常处理类ExceptionHandle,不同的框架可能不一样,对应找到即可。
/** * 钉钉开放API * https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq */ class DingdingServer { private $API_URL = "https://oapi.dingtalk.com/robot/send?access_token=4d2314f65e267474a887b287a9618a1578d3453dbdac6113542688796d553a6b"; //这个地址就是添加机器人时webhook中的地址 //发送消息 public function robotSendMsg($data = [], $msgType = 'text') { if (empty($data)) { return false; } $final_data = $data + ['msgtype' => $msgType]; $data_string = json_encode($final_data); $webhook = $this->API_URL; $result = $this->send_msg_to_dingding($webhook, $data_string); return $result; } protected function send_msg_to_dingding($remote_server, $post_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $remote_server); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=utf-8')); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 线下环境不开启curl证书验证, 如果未调通可尝试添加该代码 // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); $data = curl_exec($ch); curl_close($ch); return $data; } }
public function render($request, Throwable $e): Response { // 添加自定义异常处理机制 if (method_exists($e, 'getStatusCode')) { // 参数验证错误 if ($e instanceof ValidateException) { return json($e->getError(), 422); } // 请求异常 if ($e instanceof HttpException && request()->isAjax()) { return response($e->getMessage(), $e->getStatusCode()); } if ($e->getStatusCode() == 404) { $module = \think\facade\Request::module(); !$module and $module = 'index'; return view($module . '@public/404'); } if ($e->getStatusCode() == 500) { return parent::render($e); } } else { //这里就是获取异常信息,发送钉钉 $file = $e->getFile(); $line = $e->getLine(); $code = parent::getCode($e); $message = parent::getMessage($e); $error_message = '[' . $code . '] ErrorException in ' . $file . ' line ' . $line . PHP_EOL . $message; // 此处为钉钉server $server = new DingdingServer(); $data = [ 'text' => ['content' => $error_message], 'at' => [ // 'atMobiles' =>[$mobiles], // 'isAtAll' => true, ], ]; $server->robotSendMsg($data); return response($message, 0); } // 其他错误交给系统处理 return parent::render($e); }
效果如下:
以上就是实现钉钉机器人发送接收异常信息的全部过程了。