Client: Commands
Use client.command(...)
to send a request to the server and receive a response. This is a core mechanism for client-server interaction.
Sending commands
const result = await client.command("echo", "Hello!");
console.log(result); // "echo: Hello!"
const sum = await client.command("math:add", { a: 5, b: 3 });
console.log(sum); // 8
The method returns a Promise
that resolves with the response or rejects if the server throws or times out.
Error handling
If the server throws an error or a guard fails, the client receives it:
try {
const result = await client.command("divide", { a: 10, b: 0 });
} catch (err) {
console.error(err.message); // e.g. "Cannot divide by zero"
console.error(err.code); // e.g. "ESERVER" or your custom code
}
You can inspect .message
, .code
, and .name
on the error object.
Timeouts
The third argument to client.command(...)
is a timeout in milliseconds (not an object):
await client.command("slow-op", {}, 5000); // 5s timeout
If the command takes too long to respond, it rejects with a CodeError
:
{
message: "Command timed out after 5000ms.",
code: "ETIMEOUT",
name: "TimeoutError"
}
Best practices
- Wrap command calls in
try/catch
- Use descriptive command names like
"user:update"
or"chat:send"
- Handle command timeouts explicitly
- Validate inputs on the client before sending
Last updated on