Programmatic Error Alerting: Catching Node.js Exceptions with the SDK
In web application development, a server that is "up" is not necessarily a server that is "working." Your virtual machine hosting instance might return a 200 OK status code on its health check endpoint while your internal code scripts are silently failing.
For example, if your database query connection pool runs dry or an upstream payment gateway API starts throwing unauthorized token errors, your application middleware will fail to process business transactions. Active HTTP monitors check if your server port is open and responding, but they cannot diagnose logical exceptions occurring inside specific functions.
To catch these issues before they affect your users, you must implement programmatic error alerting. By combining standard try-catch structures with the official @pingzo/sdk package, you can trigger instant WhatsApp, Slack, or Telegram alerts the second a critical code block fails.
The Strategy: Active vs Passive Exception Reporting
Most developers configure logging tools (like Winston or Bunyan) to write error stacks to disk files or external log aggregators. While this is great for post-mortem analysis, it lacks real-time escalation.
By integrating Pingzo's SDK directly into your application's error handling structures, you convert silent logs into actionable alert events. If a critical function throws an uncaught error, your application catches it and calls the Pingzo API, which dispatches notifications directly to your phone.
Step-by-Step Implementation
Step 1: Initialize the Client SDK
First, make sure you have the official SDK installed:
npm install @pingzoapp/sdk
Next, import and initialize the client utilizing your unique monitor pingSecret:
const Pingzo = require('@pingzoapp/sdk');
const pingzo = new Pingzo('your-heartbeat-secret-id');
Step 2: Wrap Critical Code in Try-Catch Blocks
Inside your background cron jobs or data handlers, structure your blocks to trigger a failure check-in immediately when an error is caught:
async function processSubscriptionRenewal(userId) {
try {
// Core payment charging logic
await chargeUserCard(userId);
// Ping success to reset any pending alert timeouts
await pingzo.ping();
} catch (error) {
console.error('Subscription renewal failed:', error);
// Actively dispatch a failure alert with the exact error details
await pingzo.ping('fail', `SubscriptionRenewalFailed: ${error.message}`);
}
}
Global Exception Handling in Node.js
Manually wrapping every single function in try-catch blocks is tedious. To ensure you catch unexpected failures globally, integrate the SDK into your global exception hooks.
Express.js Global Error Middleware
If you use Express, add a global error handling middleware at the end of your routing chain to route internal server exceptions (HTTP 500) to your alert channels:
app.use((err, req, res, next) => {
console.error(err.stack);
// Only route critical 500 server errors, skipping user-level 400 validation issues
const statusCode = err.status || 500;
if (statusCode === 500) {
pingzo.ping('fail', `ExpressInternalError: ${err.message}`).catch(console.error);
}
res.status(statusCode).json({ error: 'Internal Server Error' });
});
Uncaught Exceptions & Unhandled Rejections
To catch crashes that would normally kill your Node.js process silently, configure global process hooks:
process.on('uncaughtException', async (error) => {
console.error('Uncaught Exception:', error);
try {
// Notify your alert channels before exiting the process
await pingzo.ping('fail', `UncaughtException: ${error.message}`);
} catch (err) {
console.error('Failed to notify Pingzo:', err);
}
process.exit(1);
});
Best Practices for Exception Alerting
- Filter Non-Critical Errors: Do not alert your team for client-side issues (like a user entering an incorrect password or a 404 page not found). Only trigger
pingzo.ping('fail')for system outages, database errors, or API timeouts. - Throttle Rapid Exceptions: If your server enters a fast loop throwing hundreds of errors per second, do not spam your alert channels. The Pingzo SDK respects rate-limits, but you should also implement local debounce logic to log details locally while sending only one warning text.
- Provide Contextual Payloads: Pass specific details in the
errorparameter (such as database client timeouts or file permission issues) to allow your on-call developer to diagnose the issue immediately from their phone.
Frequently Asked Questions
1. Does calling a failure ping resolve the monitor automatically?
No. Sending status: 'fail' flags the monitor as down and triggers active alerts. To mark the monitor as healthy again, your application must send a standard success check-in (status: 'success') once the service stabilizes.
2. Can I use this for frontend React or Vue errors?
No. The SDK requires your private pingSecret to authenticate. Storing this secret inside frontend scripts exposes it to client browsers. Use server-side logging or reverse proxy gateways to monitor frontend issues safely.
3. What happens if the Pingzo API is unreachable?
The @pingzo/sdk handles network request timeouts gracefully. Wrapping your pingzo.ping() call inside local try-catch blocks ensures that a temporary network issue on the monitoring side will not crash your main application logic.
4. How long does a failure state remain active in Pingzo?
An incident remains active until a successful ping is received or the incident is manually acknowledged and resolved inside your status dashboard.
5. Can I route different code exceptions to different alert channels?
Yes. You can create multiple Heartbeat monitors in your Pingzo dashboard (each generating a unique pingSecret) and map them to separate alert channels (e.g. database errors to WhatsApp, mail alerts to Slack).