Muhammad Fari Madyan
Hire me
Node.js & TS · part 13 of 13

Node.js & TypeScript Backend Part 13: Centralized Error Handling — Domain Errors, a NestJS Exception Filter & requestId

Part thirteen and the end of a Node.js & TypeScript series that opens with a quiz: errors that leak and errors that hide, NestJS default behaviour, domain errors with a code and status, one exception filter for AppError, ZodError, HttpException and 23505, a consistent response shape with a requestId, Express 5, and three traps.

Muhammad Fari Madyan

· 10 min read

Baca dalam Bahasa Indonesia →

Opening: Two Ways Errors Embarrass Us

The first way: a buyer sees this on screen.

TEXT
duplicate key value violates unique constraint "tiket_pesanan_unik"

A table name, a constraint name and a small sketch of your database, handed out free to anyone who opens DevTools.

The second way is the opposite. The buyer is Rp15,000 short, and what they see is:

JSON
{ "statusCode": 500, "message": "Internal server error" }

They have no idea what to do. The support team has no idea what to search for in the logs either.

The first leaks too much. The second hides too much. Both happen because every handler deals with its own errors, or does not deal with them at all. The final part of this series is about centralized error handling.


Warm-Up Quiz: Do You Still Remember?

Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.

Question 1. In NestJS with no extra filter, a controller does throw new Error('Saldo kurang: sisa 5000, butuh 20000') ("insufficient balance: 5,000 left, 20,000 needed"). What does the client get?

  • A. 400 with that message
  • B. 500 with "Internal server error"
Show the answer to question 1

B. NestJS only understands exceptions that extend HttpException. Everything else is treated as a bug and answered with {"statusCode":500,"message":"Internal server error"}. Safe, but the user loses information that would actually help them.

Question 2. What about throw new BadRequestException('Kode promo sudah kedaluwarsa') ("the promo code has expired")?

  • A. 400 with that message
  • B. 500
Show the answer to question 2

A. {"message":"Kode promo sudah kedaluwarsa","error":"Bad Request","statusCode":400}. NestJS knows how to translate HttpException and its subclasses.

Question 3. For a 500 error, what belongs in the response to the client?

  • A. err.message and err.stack, to make debugging easy
  • B. A generic message and a requestId. The details go to the logs.
Show the answer to question 3

B. Stack traces and internal error messages can leak your code structure, table names, even bits of data. A requestId links a user's complaint to the exact log line.

Question 4. Inside the filter, we check err instanceof Error first, then err instanceof AppError (where AppError extends Error). What is wrong?

  • A. Nothing
  • B. The AppError branch is never reached
Show the answer to question 4

B. Every AppError is also instanceof Error, so the first branch always catches it. Check the most specific type first, as in Part 9.

Question 5. In Express 5, an async handler throws. Does that error reach the error middleware?

  • A. Yes, automatically
  • B. No, every handler needs try/catch and next(err)
Show the answer to question 5

A. Express 5 passes rejected Promises to the error middleware. Express 4 did not, and the error became an unhandled rejection (which, as Part 2 showed, can kill the process).

What did you score? Let's take them apart.


1. The Goal: One Translator

Errors from anywhere (domain AppError, ZodError, HttpException, unique violation 23505, unexpected bugs) go into one filter. The filter logs the details and sends a response with the same shape every time: code, message, details, requestId

Click the diagram to see it full size.

Picture a hotel front desk. Whatever happens in the back (a broken air conditioner, a booking system error, a late plumber), the guest gets a polite, clear explanation from one person. The technical details go into the internal log book, not read out to the guest.

In code, that front desk is one global filter that:

  1. receives every error from every handler,
  2. translates it into the right HTTP status and message,
  3. logs the full details, only for errors that really are bugs,
  4. always answers with the same shape.

Handlers and services just throw meaningful errors. They do not need to know how to answer in HTTP.


2. Domain Errors: Business Language, Not HTTP Language

TS
export class AppError extends Error {
  constructor(
    readonly code: string,
    readonly status: number,
    message: string,
  ) {
    super(message);
    this.name = new.target.name;
  }
}

export class SaldoKurangError extends AppError {          // insufficient balance
  constructor(sisa: number, butuh: number) {
    super('SALDO_KURANG', HttpStatus.UNPROCESSABLE_ENTITY, `Saldo tidak cukup: sisa ${sisa}, butuh ${butuh}`);
  }
}

export class PesananTidakDitemukanError extends AppError { // order not found
  constructor(id: string) {
    super('PESANAN_TIDAK_DITEMUKAN', HttpStatus.NOT_FOUND, `Pesanan ${id} tidak ditemukan`);
  }
}

Why not just throw new UnprocessableEntityException(...) in the service?

Because the same service can be called from places that are not HTTP: a queue worker, a cron job, a migration script. "Insufficient balance" is a business fact. "422" is how HTTP expresses it. Keep them apart, and the translation lives in one place.

The code field (SALDO_KURANG) is for machines: the frontend can switch on it to show a "Top up" button. The message field is for people.


3. One Filter for Everything

TS
type BentukError = { status: number; code: string; message: string; details?: unknown };

function terjemahkan(err: unknown): BentukError {          // terjemahkan = translate
  if (err instanceof AppError) return { status: err.status, code: err.code, message: err.message };
  if (err instanceof ZodError) {
    return { status: 400, code: 'VALIDASI_GAGAL', message: 'Data tidak valid', details: z.flattenError(err).fieldErrors };
  }
  if (err instanceof HttpException) {
    const res = err.getResponse();
    const message = typeof res === 'object' && res !== null && 'message' in res ? res.message : err.message;
    return { status: err.getStatus(), code: `HTTP_${err.getStatus()}`, message: String(message) };
  }
  if (typeof err === 'object' && err !== null && 'code' in err && err.code === '23505') {
    return { status: 409, code: 'SUDAH_ADA', message: 'Data yang sama sudah ada' };
  }
  return { status: 500, code: 'INTERNAL', message: 'Terjadi kesalahan di server' };
}

@Catch()
export class SemuaErrorFilter implements ExceptionFilter {   // "all errors" filter
  private readonly logger = new Logger('Error');

  catch(err: unknown, host: ArgumentsHost) {
    const http = host.switchToHttp();
    const req = http.getRequest<Request>();
    const res = http.getResponse<Response>();
    const requestId = req.header('x-request-id') ?? randomUUID();
    const hasil = terjemahkan(err);

    if (hasil.status >= 500) {
      // The full details only go to the logs, never to the client.
      this.logger.error(`${req.method} ${req.url} requestId=${requestId}`, err instanceof Error ? err.stack : String(err));
    }
    res.status(hasil.status).json({ error: { code: hasil.code, message: hasil.message, details: hasil.details, requestId } });
  }
}

// main.ts
app.useGlobalFilters(new SemuaErrorFilter());

Notice that terjemahkan takes unknown (Part 7) and narrows from the most specific type to the most general (Part 9). @Catch() with no arguments means "catch everything".

I set up six routes, each throwing a different kind of error, and called them with an x-request-id: req-42 header:

TEXT
/bayar     {"error":{"code":"SALDO_KURANG","message":"Saldo tidak cukup: sisa 5000, butuh 20000","requestId":"req-42"}}  [422]
/pesanan   {"error":{"code":"PESANAN_TIDAK_DITEMUKAN","message":"Pesanan INV-404 tidak ditemukan","requestId":"req-42"}}  [404]
/promo     {"error":{"code":"HTTP_400","message":"Kode promo sudah kedaluwarsa","requestId":"req-42"}}  [400]
/validasi  {"error":{"code":"VALIDASI_GAGAL","message":"Data tidak valid","details":{"jumlahTiket":["Too small: expected number to be >=1"]},"requestId":"req-42"}}  [400]
/duplikat  {"error":{"code":"SUDAH_ADA","message":"Data yang sama sudah ada","requestId":"req-42"}}  [409]
/bug       {"error":{"code":"INTERNAL","message":"Terjadi kesalahan di server","requestId":"req-42"}}  [500]

And only /bug reaches the logs:

TEXT
[Nest] ERROR [Error] GET /bug requestId=req-42
TypeError: Cannot read properties of undefined (reading 'nama')
    at DompetController.bug (.../dist/main.js:84:49)

Compare that with the two problems in the opening:

  • /duplikat (duplicate) used to leak the constraint name. Now it is a 409 with a polite message ("the same data already exists").
  • /bayar (pay) used to be a 500 with no explanation. Now it is a 422 with a SALDO_KURANG code the app can act on.
  • /bug is still a 500 with no details, but its requestId points straight to the stack trace in the logs.

4. A Consistent Response Shape

Every error now has the same shape:

JSON
{
  "error": {
    "code": "SALDO_KURANG",
    "message": "Saldo tidak cukup: sisa 5000, butuh 20000",
    "requestId": "req-42"
  }
}

The details field only appears when there is something to explain per field, such as a validation failure. For the frontend team, this means one function to read every error. For the support team, it means one question to the user: "Could you send me the requestId?"

A requestId is most useful when it is created at the very front (the load balancer or the first middleware), passed into every log, and sent back to the client. On Cloud Run, every request also carries an X-Cloud-Trace-Context header you can use to link logs with traces.

Using Express without NestJS

Same principle: one error middleware with four parameters, registered last. In Express 5, errors from async handlers reach it automatically (question 5):

JS
app.get('/bayar', async () => {
  await new Promise((r) => setTimeout(r, 10));
  throw new Error('Saldo kurang'); // thrown from an async handler
});

// Error middleware: four parameters, registered last.
app.use((err, req, res, _next) => {
  console.error(`${req.method} ${req.url}:`, err.message);
  res.status(500).json({ error: { code: 'INTERNAL', message: 'Terjadi kesalahan di server' } });
});
TEXT
GET /bayar: Saldo kurang
500 {"error":{"code":"INTERNAL","message":"Terjadi kesalahan di server"}}

The body of that middleware can use exactly the same terjemahkan function.


5. Three Error Handling Traps

Trap 1: swallowing errors

TS
try {
  await sendConfirmationEmail(order);
} catch {
  // later
}

A swallowed error never reaches the logs, never triggers an alert, and cannot be searched for. If it is allowed to fail, at least log it at warn level. If it is not allowed to fail, let it rise to the filter.

Trap 2: throwing strings

TS
throw 'insufficient balance';

No stack trace, it fails instanceof Error, and the filter can only treat it as a 500 bug. Always throw an Error object or a subclass. This is also why catch (err) is unknown (Part 7).

Trap 3: logging everything as ERROR

If every 404 and 422 goes into the logs as ERROR, alerts fire all day and the team stops paying attention. Then a real 500 arrives and nobody notices. That is why the filter above only logs status >= 500 as an error. A 4xx is a client mistake: count it as a metric or log it at a lower level.


Summary

  • Two failures: leaking internal details, or hiding everything behind a 500.
  • NestJS default: HttpException is translated, everything else becomes 500 Internal server error.
  • Domain errors (AppError with code and status) in services. Business language, not HTTP.
  • One @Catch() filter translates everything: AppError, ZodError, HttpException, 23505 → 409, the rest → 500.
  • A consistent response shape: { error: { code, message, details, requestId } }.
  • Log details only for 5xx, with the requestId. Never send a stack trace to the client.
  • Traps: swallowing errors, throwing strings, logging every 4xx as ERROR.

Closing the Series

Neither message from the opening will show up again. A buyer who is short on balance knows what to do, and no table names leak to the browser.

This is the final part of Node.js & TypeScript Backend. In one line per section:

  • Node.js: do not block the event loop, cap parallelism, keep state outside the process, stop politely, watch for memory that keeps climbing, and respect backpressure.
  • TypeScript: unknown at the door, validate at runtime, model states with discriminated unions, and let generics and utility types cut the repetition.
  • Backend: make operations safe to repeat, and translate every error in one place.

Every part opens with a quiz. If one day you are unsure about a topic, open its part and try the quiz first. Get everything right and you do not need to reread it. Miss one, and you know exactly which part to refresh.

Grab your coffee, and thank you for following this series to the end!

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 12Idempotencyseries completeBack to all articles →

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan