TPY Error Handling and Debugging
Why Error Handling Matters
Proper error handling ensures your bot behaves gracefully when things go wrong, providing a better user experience and making debugging easier for you.
Basic Try-Catch Blocks
Use try-catch blocks to handle exceptions and prevent your bot from crashing:
try {
// Risky operation
var data = JSON.parse(userInput);
bot.sendMessage("Data processed successfully!");
} catch (error) {
// Handle the error gracefully
bot.sendMessage("Sorry, I couldn't process your request. Please check your input.");
// Log for debugging
console.log("Error: " + error);
}
API Error Handling
External APIs can fail for many reasons. Always handle these cases:
try {
var response = http.get("https://api.example.com/data");
var data = JSON.parse(response);
bot.sendMessage("Data received: " + data.value);
} catch (error) {
bot.sendMessage("Service temporarily unavailable. Please try again later.");
console.log("API Error Details: " + error);
// Optional: Notify admin
if (User.getProperty("role") === "admin") {
bot.sendMessage("Admin alert: API failed - " + error);
}
}
Input Validation
Validate user input before processing to prevent errors:
function isValidEmail(email) {
var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
function isValidNumber(num) {
return !isNaN(num) && num > 0;
}
// Usage
var userInput = request.text;
if (isValidEmail(userInput)) {
User.setProperty("email", userInput);
bot.sendMessage("Email saved!");
} else {
bot.sendMessage("Please enter a valid email address.");
}
Debugging with Console Logs
Use console.log to debug your code. These logs appear in your bot's logs for debugging purposes.
console.log("=== Command Started ===");
console.log("User ID: " + request.userId);
console.log("Input: " + request.text);
// Your bot logic
var result = processUserRequest(request.text);
console.log("Result: " + result);
console.log("=== Command Finished ===");
Graceful Degradation
Design your bot to work even when some features fail:
// Try premium feature, fall back to basic
var userData = null;
try {
userData = getPremiumUserData(userId);
} catch (error) {
console.log("Premium feature failed, using basic");
userData = getBasicUserData(userId);
}
if (userData) {
displayUserData(userData);
} else {
bot.sendMessage("Unable to load user data at this time.");
}
Common Error Patterns
- Network errors - API timeouts or connection issues
- Parsing errors - Invalid JSON or malformed data
- Type errors - Using wrong data types
- Reference errors - Accessing undefined variables
- Permission errors - Insufficient rights for operations
Error Logging Strategy
Implement a consistent error logging strategy:
function logError(error, context) {
var logEntry = {
timestamp: Date.now(),
error: error.toString(),
context: context,
userId: request.userId,
command: request.command
};
console.log(JSON.stringify(logEntry));
// Optionally store errors for analysis
var errorLog = User.getProperty("system_errors") || [];
errorLog.push(logEntry);
if (errorLog.length > 100) errorLog.shift(); // Keep last 100 errors
User.setProperty("system_errors", errorLog);
}
// Usage
try {
// risky operation
} catch (error) {
logError(error, "fetching_user_data");
bot.sendMessage("An error occurred. Our team has been notified.");
}
Learn More
For more debugging techniques, visit:
🔗 Telebot Creator Documentation
Testing Tips
Always test your error handling by simulating failures. Try disconnecting from the internet, using invalid inputs, or causing API errors to see how your bot responds.
📚 Source
This tutorial is based on the official Telebot Creator Documentation. Visit their site for the most up-to-date information and advanced guides.