Consistent Response Formats, Error Codes, and Exception Handling

Define stable success and failure structures and handle exception responses centrally

🎯 Introduction

By the end of this article, you will be able to keep success and failure responses consistent and centralize exception handling with Express error middleware.

🧾 Define the response format first

Place successful results in data:

{"data":{"id":1,"name":"Ming"}}

For failures, provide a stable error code and a readable message:

{"error":{"code":"NAME_TAKEN","message":"Name is already taken"}}

Application error codes distinguish specific causes that share an HTTP status. The frontend uses code to choose behavior and message for display. Field names are a project convention; consistency across endpoints is what matters.


🚦 Return expected business failures directly

Create error-app.mjs:

error-app.mjs
import express from 'express';

export const app = express();
app.use(express.json({ limit: '16kb' }));

This endpoint simulates a branch where a name is already taken:

error-app.mjs
app.post('/users', (req, res) => {
    res.status(409).json({
        error: { code: 'NAME_TAKEN', message: 'Name is already taken' }
    });
});

Requests receive 409 and the agreed error object. A real application checks the database before choosing this branch. Here it always returns a failure to verify the response structure.


Check the response to an unexpected failure

Add an intentionally failing asynchronous endpoint:

error-app.mjs
app.get('/failure', async (req, res) => {
    throw new Error('Simulated internal operation failure');
});

Requesting /failure reaches the shared error handler. The client should receive 500 with a generic message. See Express Error Handling for asynchronous error propagation; here we focus on the final status and fields.


🔎 Decide what to tell the client first

Malformed JSON, an oversized body, and an internal failure need different messages. Put error classification in a separate function, then let error middleware send the response.

Create error-handler.mjs and define two request body errors:

error-handler.mjs
const inputErrors = {
    'entity.parse.failed': {
        status: 400, code: 'INVALID_JSON', message: 'Invalid JSON'
    },
    'entity.too.large': {
        status: 413, code: 'BODY_TOO_LARGE', message: 'Request body is too large'
    }
};

When express.json() cannot read the body, the error's type identifies the cause. entity.parse.failed means malformed JSON; entity.too.large means the body exceeds the earlier 16 KB limit. In the table, status is the HTTP status code, while code and message are returned to the client.

Next, add the classification function in the same file:

error-handler.mjs
function getErrorResponse(error) {
    const inputError = inputErrors[error.type];
    if (inputError) return inputError;
    console.error(error);
    return {
        status: 500, code: 'INTERNAL_ERROR', message: 'The service is temporarily unable to process the request'
    };
}

For malformed JSON, it returns the entry with status 400. If no entry matches, it treats the error as internal: the terminal logs the actual error, while the client receives a generic message to avoid exposing details such as database addresses. This function only chooses the response content; it does not send it.


📤 Send the response through error middleware

Error middleware is a function Express calls when earlier processing fails. Export it from the same file:

error-handler.mjs
export function errorHandler(error, req, res, next) {
    if (res.headersSent) return next(error);
    const result = getErrorResponse(error);
    res.status(result.status).json({
        error: { code: result.code, message: result.message }
    });
}

Express identifies error middleware by its four parameters: error is the exception, req is the current request, res sends the response, and next forwards the error. Keep the req parameter in its position even if it is unused.

After getErrorResponse chooses the content, res.status sets the HTTP status and res.json sends the error object. For malformed JSON, the status is 400 and the body is:

{"error":{"code":"INVALID_JSON","message":"Invalid JSON"}}

Why check headersSent first?

res.headersSent indicates whether response headers have already been sent. For example, if reading a file fails after a download begins, you cannot reset the status and send a separate JSON error.

In that case, return next(error) forwards the error to subsequent Express error handling. There is no other error middleware in this example, so the framework's default handler ultimately closes the connection. return stops the current function from sending JSON. The normal error response runs only when the response has not started.


🔗 Register it after all routes

Return to error-app.mjs and add this after the routes:

error-app.mjs
import { errorHandler } from './error-handler.mjs';

app.use((req, res) => {
    res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Endpoint not found' } });
});
app.use(errorHandler);

404 means no route responded. It is not an automatically thrown exception, so ordinary middleware handles it. Error middleware belongs afterward so it can receive errors from earlier routes or parsing.


🧪 Verify different failures

Create the startup file:

error-server.mjs
import { app } from './error-app.mjs';

app.listen(3000, '127.0.0.1');

Run node error-server.mjs and check:

RequestExpected statuserror.code
POST /users, valid JSON409NAME_TAKEN
POST /users, malformed JSON400INVALID_JSON
GET /failure500INTERNAL_ERROR
GET /missing404NOT_FOUND

For example, check an internal failure:

curl -i http://127.0.0.1:3000/failure

The client receives a generic message, while the server terminal shows the simulated exception. Preserve HTTP failure statuses rather than changing every status to 200 for a uniform body format.


❓ Questions and Answers

Q1: Does every error need an Error subclass?

No. Simple business branches can respond directly, while shared error middleware handles exceptions. Introduce application error types when a clear need arises.

Q2: Should every layer log an error?

No. Log an exception at its final handling point to avoid duplicate logs that complicate investigation.

Q3: Does 204 also need data?

No. A 204 response has no body. Response format conventions must respect status code semantics.


🧪 Practice

Change the NAME_TAKEN message and confirm that the frontend can still use the code. Send malformed JSON and observe whether it is rejected before the business endpoint runs.

// Write your code or record your results here