discordjs / RPC

A simple RPC client for Discord
MIT License
466 stars 191 forks source link

TypeError Cannot read property 'write' of null #82

Closed AxelTerizaki closed 4 years ago

AxelTerizaki commented 4 years ago

Hello !

I implemented DIscordRPC in my app, and I must say it was very easy to do. Thanks for that :)

Some of our users' seem to run into an error though as Sentry occasionally sends us some alerts about the same kind of error as in this issue's topic.

It occurs on line 152 of src/transports/ipc.js :

  send(data, op = OPCodes.FRAME) {
    this.socket.write(encode(op, data));
  }

So I assume this.socket isn't properly initialized as if connect() didn't get triggered for some reason (or before send() is used, at least.)

Not sure if I can do anything about it so I wanted to open this issue.

Here's the related code we use to connect and send activity through Discord RPC :

let rpc: any;

discordRPC.register(clientId);

export function setDiscordActivity(activityType: 'song' | 'idle', activityData?: any) {
    try {
        if (!getConfig().Online.Discord.DisplayActivity || !rpc) return;
        const startTimestamp = new Date();
        let activity: string;
        let activityDetail = 'Zzz...';
        if (activityType === 'idle') {
            activity = sample(i18next.t('DISCORD.IDLING', {returnObjects: true}));
        }
        if (activityType === 'song') {
            activity = activityData.title,
            activityDetail = activityData.singer;
        }
        rpc.setActivity({
            details: activity.substring(0, 128),
            state: activityDetail.substring(0, 128),
            startTimestamp,
            largeImageKey: 'nanami-smile',
            largeImageText: 'Karaoke Mugen',
            smallImageKey: activityType === 'song' ? 'play' : 'pause',
            smallImageText: `Version ${version.number} - ${version.name}`,
            instance: false,
        });
    } catch(err) {
        sentry.error(err, 'Warning');
        // Non-fatal
    }
}

export function stopDiscordRPC() {
    if (rpc) {
        rpc.clearActivity();
        rpc.destroy();
        rpc = null;
    }
}

export function initDiscordRPC() {
    if (rpc || !getConfig().Online.Discord.DisplayActivity) return;
    rpc = new discordRPC.Client({ transport: 'ipc' });

    rpc.on('ready', () => {
        setDiscordActivity('idle');
        // activity can only be set every 15 seconds
    });
    rpc.login({ clientId }).catch(console.error);

}

Are we doing something wrong that could trigger this error?

Thanks in advance for your help.

AxelTerizaki commented 4 years ago

I think I got it covered. I wasn't try/catching enough and taking into account people could close DIscord (or it could have crashed) while my app was running. Sorry for opening an issue about that.