Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Middleware and Authentication

Error Handling and Input Validation

Keep a Socket.IO server alive. Wrap handlers so exceptions cannot crash the process, handle async errors, report errors to clients, validate and sanitize chat input, and log what matters.

A web server that handles requests has a safety net: Express catches an error in a route and returns a 500 for that one request. Socket.IO has no such net for event handlers. If a handler throws and nothing catches it, the exception becomes an uncaught exception and Node.js terminates the whole process. One badly formed message from one client can then disconnect every user. This lesson shows how to prevent that, how to report problems to the right client, and how to make user input safe.

Where errors come from

  • Bad input: a missing field, wrong type or oversized value (payload.text.trim() when payload is undefined).
  • Failing dependencies: database down, an HTTP call times out, JSON.parse of a stored value fails.
  • Your own bugs: typos, wrong assumptions.
  • Async mistakes: an async handler that rejects with nobody awaiting it. Since Node 15 an unhandled promise rejection also terminates the process by default.

The first rule is therefore simple: no handler may throw or reject unhandled.

A wrapper that catches everything

Instead of writing try/catch in every handler, write one higher-order function that wraps a handler, handles sync and async failures, logs them and tells the client in a safe way:

JavaScript
const safe = (handler) => async (...args) => {
  try {
    await handler(...args);
  } catch (err) {
    console.error('handler failed:', err);
    // tell this client something generic; never leak err.message / stack
  }
};

Because acknowledgement callbacks (the last function argument) are very handy for error reporting, a fuller wrapper can use them when present. The runnable example below shows the pattern on the stand-in, including a handler that throws synchronously and one that rejects asynchronously, and shows that the "server" keeps serving other events afterwards.

Node.js A safe handler wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Case 2 and case 4 would have crashed an unprotected server; here the client receives only internal error while the real message (which mentions a table name) stays in the server log. Case 5 shows how to deliberately expose a message that is safe for users: mark such errors (expose: true) and send everything else generically.

Do not "fix" crashes by adding process.on('uncaughtException', () => {}) that swallows everything. After an uncaught exception the process may be in an unknown state. Log it, finish in-flight work if you can, and exit so your process manager restarts a clean instance. Fix the missing try/catch instead.

Telling the client

Pick one convention and use it everywhere so the client code stays simple:

  1. Acknowledgement result for request/response-style events: callback({ ok: false, error: '...' }). The sender gets the reply to exactly the action it took. (Acknowledgements get a full chapter later in this course.)
  2. A dedicated error event for failures that are not tied to a reply: socket.emit('app:error', { code, message }).
  3. The connect_error event for failures during the connection handshake (from middleware).

Use stable error codes (VALIDATION_FAILED, NOT_ALLOWED, RATE_LIMITED) for programs and short human messages for people. On the client, one global listener can show a toast for every app:error.

Validate with a schema library

Hand-written checks get long quickly. For real projects use a schema library; the validation function either returns the clean, typed object or throws. A sketch with Zod (read-only, not available in this site's editors):

JavaScript
import { z } from 'zod';

const sendMessage = z.object({
  room: z.string().regex(/^room:\d+$/),
  text: z.string().trim().min(1).max(500),
});

socket.on('message:send', safe(async (raw) => {
  const { room, text } = sendMessage.parse(raw); // throws a ZodError on bad input
  if (!socket.rooms.has(room)) throw Object.assign(new Error('join the room first'), { expose: true });
  io.to(room).emit('message:new', { room, text, from: socket.data.userId });
}));

The schema trims whitespace, enforces lengths, and rejects extra surprises, so the rest of the handler can assume clean data.

Sanitizing text and avoiding XSS

Chat messages, usernames and room titles are shown to other people's browsers. If you insert them into the page as HTML, a user can send <img src=x onerror=...> and run scripts in every viewer's browser: cross-site scripting (XSS). Defences, in order of importance:

  1. Render user text with textContent (or your framework's normal text binding such as React's ), never with innerHTML.
  2. If you must allow formatting (Markdown or links), sanitize on output with a vetted library.
  3. Escape on the server only when the data will be placed into HTML there (for example emails); do not store pre-escaped text in your database, because you will double-escape it later.
  4. Limit length and strip control characters at the edge, as part of validation.

This runnable helper shows what escaping does, plus a normalization step for control characters and length:

Node.js Escaping and normalizing user text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The escaped column is what is safe to put inside HTML. With textContent the browser does this for you, which is why it is the preferred approach.

What to log

Log enough to debug without leaking secrets: event name, socket.id, socket.data.userId, a request id, the error and its stack. Do not log tokens, passwords or full payloads of private messages. In production send logs to a central place and alert on spikes of app:error and of connect_error (often a sign of a broken deploy or an attack).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A socket.on handler throws and nothing catches it. What happens?

    There is no per-event safety net, so an uncaught exception ends the process and disconnects every client.
  2. 2. What should the client receive when a database error message mentions internal table names?

    Internal details help attackers. Log them on the server and return a safe generic error.
  3. 3. How should user-supplied chat text be displayed in the browser?

    textContent treats the text as plain text, so markup in a message cannot run scripts.
  4. 4. Why is process.on('uncaughtException', () => {}) a bad fix?

    Swallowing the error keeps a possibly corrupt process running. Catch errors in handlers instead.

Summary

  • Event handlers have no safety net: wrap them so sync throws and rejected promises are caught.
  • Report errors to the sender with an acknowledgement or an app:error event; use stable codes and never leak internals.
  • Validate and normalize every payload, ideally with a schema library.
  • Render user text with textContent to prevent XSS; sanitize only where HTML is really needed.
  • Log events and ids but not secrets, and let a supervisor restart the process after truly fatal errors.

Next: Scaling Socket.IO Servers