Discord Bot Error Handling Best Practices
Proper error handling is crucial for a reliable Discord bot. This guide covers common error scenarios and how to handle them gracefully.
Why Error Handling Matters
- User Experience: Prevent crashes and show helpful messages
- Debugging: Log errors for troubleshooting
- Stability: Keep the bot running even when things go wrong
- Security: Prevent exposing sensitive information in error messages
Common Error Types
API Errors
Discord API errors have specific codes:
const { DiscordAPIError } = require('discord.js');
try { await message.delete();} catch (error) { if (error instanceof DiscordAPIError) { switch (error.code) { case 10008: console.log('Message not found'); break; case 50013: console.log('Missing permissions'); break; case 50035: console.log('Invalid form body'); break; default: console.error('API Error:', error.code, error.message); } }}Permission Errors
Always check permissions before performing actions:
async function deleteMessage(message) { const botMember = message.guild.members.me;
if (!botMember.permissions.has('ManageMessages')) { await message.reply('I need the Manage Messages permission!'); return; }
try { await message.delete(); } catch (error) { console.error('Failed to delete message:', error); }}Global Error Handlers
Process-Level Handlers
process.on('unhandledRejection', (error) => { console.error('Unhandled promise rejection:', error);});
process.on('uncaughtException', (error) => { console.error('Uncaught exception:', error); process.exit(1);});Best Practices Summary
- Always use try-catch for async operations
- Check permissions before actions
- Validate user input at multiple levels
- Log errors with context information
- Show user-friendly messages, log technical details
This is an update test