onError
Method onError
The onError
method is called when an error occurs while executing a command. This method can be overridden in child classes to handle errors differently.
Parameters
message: UserMessageContext
: an object that contains information about the incoming message.error: any
: an error object that was thrown during command execution.
Return Value
This method should return some result. By default, it simply throws an error, which can lead to the bot crashing. However, if this method is overridden in a child class, you can implement some error handling logic and return control back to the main application code.
Example usage
import { Command } from "./command";
import { UserMessageContext } from "../contexts";
export class MyCommand extends Command {
public async execute(message: UserMessageContext): Promise<void> {
// some code that may throw an error
}
public onError(message: UserMessageContext, error: any): void {
console.log(`Caught an error while executing command ${this.params.name}: ${error.message}`);
message.reply("Sorry, something went wrong while executing your command.");
}
}
In this example, we created a new MyCommand
class that inherits from the Command
class. We have overridden the execute
method to perform some logic that may throw an error. We also overrode the onError
method to output the appropriate messages to the console when an error occurs and send a reply to the user.