Unhandled Errors

When using the asynchronous interface, errors can occur that are not thrown to the user. For example, when a message with invalid JSON data was received, the error occurs in the process of parsing its data inside of the AMPS JavaScript Client. Consider the following example:

const onMessage = message => console.log(message.data);
await client.subscribe(onMessage, 'pokes', '/Pokee LIKE ' + userId);

In this example, we set up a subscription to wait for messages on the pokes topic, whose Pokee tag begins with our user ID. When messages arrive, we print a message out to the console.

Inside of the AMPS client, the client received an message that contains invalid JSON data that cannot be parsed. When the error occurs, there is no handler for it to be reported to, and by default it is ignored.

In applications where it is important to deal with every issue that occurs in using AMPS, you can set an error handler via Client.errorHandler() that receives these otherwise-unhandled errors and exceptions. Making the modifications shown in the example below, to our previous example, will allow those errors to be caught and handled. In this case we are simply printing those caught errors out to the console.

const onMessage = message => console.log(message.data);

// This time, let's add the error handler
client.errorHandler(err => console.error('Error occurred:', err));

await client.subscribe(onMessage, 'pokes', '/Pokee LIKE ' + userId);

In this example we have added a call to client.errorHandler(), registering a simple function that writes the text of the error out to the console. If errors are thrown in the message handler, those errors are written to the console.

Last updated