Can I add custom error handling and error logging to my CloudCode tasks?

Is it possible to add custom error handling / logging to my CloudCode tasks?

Yes.

  1. Create an error model for the task which is not synced to user devices.
  2. When entering a task, create an object for that model.
  3. When you hit an error, log the traceID of the task, the object that entered the task (or user that triggered it) into separate, searchable fields. Also log the error message itself in the body of the object.

This should give the developer or user all of the info they need, and also allow the developer to use built-in audits to track down the specific execution if errors occur.

Thanks @JasonB .

Is it possible to integrate with existing Error handling services, like rollbar or honey-badger?

Yes, An example would be if you wanted to use, e.g. Rollbar:

export async function run() {
    // Your code here
    const ROLLBAR = new Rollbar({
        accessToken: "", // insert rollbar access token here
        captureUncaught: true,
        captureUnhandledRejections: true,
        environment: CloudCode.task.env
    });

    //Setup Rollbar for cloud code events
    this.on('beforeTimeout', () => {
        ROLLBAR.critical(`${CloudCode.task.name} - Script timeout imminent!`, { custom: { context: this } });
    });
    this.on('highMemory', () => {
        ROLLBAR.critical(`${CloudCode.task.name} - High memory usage!`, { custom: { context: this, memory: process.memoryUsage() } });
    });

    try { // try some code
        const recipient = await DB.user.first();

        await recipient.save();

    } catch(error) { // catch errors that crop up
        if(this.source !== CloudCode.EDITOR_TEST){
            await ROLLBAR.error(`Cloud Code - ${CloudCode.task.name} - ${error}`, { custom: { context: this, error: error } });
        }

        console.error(error);
        throw error;
    }

}
4 Likes