How should you handle errors returned by database operations within a Go web service to ensure graceful degradation and avoid crashing the entire service?

Go & Rust interview question for Advanced practice.

Answer

Log the detailed error, and return an appropriate HTTP error code (e.g., 500 Internal Server Error) to the client with a generic message.

Explanation

Option C is the correct approach. A database error is a server-side failure. You should log the full, detailed error message on the server for debugging purposes. However, you should not expose these details to the client, as they can reveal information about your internal infrastructure. Instead, return a generic 500 Internal Server Error to the client. Panicking (A) is too extreme and brings down the whole service. Ignoring errors (B) is dangerous and leads to incorrect behavior. Returning raw errors (D) is a security risk.

Related Questions