How to Handle API Errors Without Leaking Internals

Every API returns errors. The difference between a good API and a careless one is what those errors reveal. A message like “column users.email does not exist” tells an attacker your table and column names. A stack trace tells them your framework, your file paths, and the libraries you run. Learning how to handle API errors without leaking internals is mostly a matter of deciding, once, what an error looks like, and then making every route use that shape.

Handle API errors with one consistent shape

Pick a single error format and use it everywhere. A common shape is a JSON object with a stable machine-readable code, a short human-readable message, and optional details that are safe to show. Clients can then switch on the code instead of parsing message text, and your team can change the wording without breaking anyone. The shape should stay the same across success and failure paths, so a client never has to guess whether a response is an object, an array, or a plain string. When you compare REST vs GraphQL, notice that both styles need this decision; GraphQL returns errors in its own envelope, but the same rule applies to what goes inside it.

Use status codes that mean something

Status codes are the first thing a client reads, so make them honest. 400 means the request itself was wrong. 401 means no valid credentials were presented. 403 means the caller is authenticated but not allowed. 404 means the resource does not exist. 409 means the request conflicts with current state, like creating a duplicate. 422 works for validation failures when you want to separate them from malformed requests. 500 means your server failed, and the client cannot fix it by retrying the same request. Keep a short list of codes your API actually uses and document them. A client that sees 500 for a validation error will retry a request that can never succeed.

The error shape stays the same in every route

The easiest way to keep errors consistent is to stop writing error responses inside route handlers. Build one error-handling middleware that sits at the end of the chain and formats every error the same way. Handlers throw a typed error, or pass one to next(), and the middleware decides the status code and the body. This also gives you one place to add the behaviour you want everywhere: a request ID in the response, a log line, and a check that no internal detail slips through. If a new route forgets to handle an error, the middleware still catches it.

Log the full error, send the short version

Your team needs the detail. Your clients do not. Log the full error on the server: the stack trace, the request path, the user ID, and the values that caused the failure. Then send the client only the stable code and a generic message. This split is the core habit behind safe error handling. A 500 response that says “Something went wrong. Reference: req_9f3k2” gives the client something to report and gives your team something to search for, without handing an attacker a map of your code. Make sure the log line itself never contains a password, token, or full request body.

Never send stack traces to clients

Never send stack traces to clients, in any environment that real users can reach. Stack traces name files, line numbers, function names, and package versions. They also change with every deploy, so clients cannot rely on them anyway. Check this in staging by forcing an error and reading the raw response, because frameworks often include a stack trace in development mode and the setting that disables it is easy to miss. The same rule covers database errors: catch them at the boundary of your data layer and convert them into a generic error before they travel any further.

Do not confirm what exists

Error messages can leak information even when they contain no technical detail. A login endpoint that says “email not found” for one input and “wrong password” for another tells an attacker which email addresses have accounts. Return the same message for both cases. The same applies to password reset: always answer as if the email was sent. Resource endpoints should behave the same way. If a user asks for an order that is not theirs, return 404, not 403, so the response does not confirm the order exists. This is a small detail that closes a real enumeration hole.

Validation errors deserve detail, carefully

Validation errors are the exception to the “say less” rule. A client that sent a bad field needs to know which field failed and why, or it cannot fix the request. Return the field name and a short reason, like “email must be a valid email address”. Keep the reasons generic and tied to your public contract, not to your database schema. A message that says “value too long for column name varchar(50)” leaks schema detail; “name must be 50 characters or fewer” says the same thing safely. When you design these messages, imagine reading them as a stranger who knows nothing about your system.

Handle the errors you did not expect

Some errors arrive from places your code never anticipated: a database connection drops, a third-party service times out, a disk fills up. Your error middleware needs a fallback for these: log the full detail, return a 500 with a generic message and a request ID, and make sure the process stays alive. In Node.js, an uncaught exception in a request handler can crash the process if nothing catches it, so the middleware is also your last line of defence against downtime. Test this path on purpose. Kill the database connection in a staging environment and watch what the client receives; if the answer is a stack trace or a hung request, the fallback is not working.

What to check before you ship

Before a new endpoint ships, send it four requests: one valid, one with a bad field, one without auth, and one that triggers a server-side failure. Read each response as an attacker would. If any response names a table, a file, a library version, or a user that should stay hidden, fix it in the error middleware, not in the route. Repeat the check after framework upgrades, because default error output changes between versions. Safe errors are not a feature you build once; they are a property you keep checking. And when you need to trace a failure on your own machine, debugging JavaScript in Chrome DevTools is a useful skill for the client side of the same problem, while your server logs cover the rest.

Good error handling is invisible to honest users and unhelpful to attackers. That is the whole goal: clients get enough information to fix their requests, your team gets everything it needs in the logs, and nothing about your internals ever crosses the wire. If you are still deciding how requests and responses should flow in your API, reading how HTTP requests really work will make the status codes and the middleware order in this article feel obvious.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.