Junior — Middle
What methods can be used to prevent a 500 error in case of timeout when waiting for a database response?
sobes.tech AI
Answer from AI
To prevent a 500 error caused by a timeout when waiting for a response from the database in Go, several approaches can be used:
-
Timeout context — use
context.WithTimeoutto limit the execution time of the database query. -
Connection pool — properly configure the connection pool to avoid blocking and delays.
-
Error handling — correctly handle timeout errors and return understandable responses to the client.
Example of using a timeout context:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := db.QueryRowContext(ctx, "SELECT ...").Scan(&result)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
// handle timeout
} else {
// handle other errors
}
}
This approach helps avoid hangs and control the response wait time from the database.