I'm working on an API service and I'm having a dilemma on how to implement 500 reponses. I'm not certain on which is best between sending the actual error cause or just a generic "internal server error" message.
The arguments I can see for each are:
Explicit error description: The cause is clear to any client consuming the API and easier feedback can be given to the API dev when the exact error cause is known.
Generic error: The underlying implementation is hidden from clients as they do not need to know how the API works behind-the-scenes. From that perspective, it could also probably be better security against malicious clients.
Which is generally seen as a better practice, and are there also other reasons to consider?
CodePudding user response:
The best practice would be to throw a generic error message returning as little information to the client as possible. If additional context is required for debugging purposes, you can write that context to a server-side log.
For example, in C#:
try
{
// Do something
}
catch (Exception ex)
{
Log.Error("Error details", ex);
return StatusCode(500, "Something went wrong");
}
Remember to obfuscate any confidential information (like passwords) if you log to the server; you should log just enough relevant information to diagnose and resolve the problem.
CodePudding user response:
The approach I take with this (in Node.js) is as follows:
- Uncaught errors get turned into
InternalServerError
. exceptions. - We have a middleware that turns this into the standard
application/problem json
error response. - In dev/testing, the error response contains the message from the thrown error.
- In prod, this gets turned into a generic error message that leaks no information about internals.
- In all of cases we log the real message.
- In some system I've built we emitted an 'id' in the error response corresponding to an id in the log, making it easier for someone to report a problem and us to look up related information.