Search code examples
phplaraveltry-catchtelegram-bot

how to catch any error in telegram bot?


I am wondering how to catch any possible error in telegram bot API. because of when an error occurs, telegram sticks to it and does not answering another requests. I want to get rid if any errors that may cause by bugs in my code,or web-services I am using or blocking the bot or... how can I avoid from sticking to one request in telegram bot API with PHP? I think what I need is something like bellow code but more general for any kind of error:

try {

    $telegram->sendMessage([
        'chat_id'                  => '<PERSONS_ID>',
        'text'                     => 'Here is some text',
    ]);
} catch (TelegramResponseException $e) {
    $errorData = $e->getResponseData();

    if ($errorData['ok'] === false) {
        $telegram->sendMessage([
            'chat_id' => '<ADMINISTRATOR ID>',
            'text'    => 'There was an error for a user. ' . $errorData['error_code'] . ' ' . $errorData['description'],
        ]);
    }
}

Solution

  • finally I solved the issue by a trick.I created another bot for error handling. So I have a bot X and an error handling bot Y. here the POST method I receive webhooks from telegram:

    public function postWebhook(Request $request)
    
        { .....
            try
            { ....
             bot X token
             everything the bot want to do...
            }
            catch (\Exception $e) 
            {
                 bot Y send me the probable problem in my code....
            }
            catch (Throwable $e)
            {
                   bot Y send me the probable problem in telegram such 
                   as blocking ,..
            }
    

    now I prevent sticking in an error and bot works great. even I am notified if a part of my web service has problem or my code has a mistake.