Sobes.tech
Junior — Middle

Milliseid meetodeid saab kasutada 500 vea vältimiseks andmebaasi vastuse aegumise korral

sobes.tech AI

Vastus AI-lt

To prevent a 500 error caused by a timeout while waiting for a response from the database in Go, several approaches can be used:

  1. Context with timeout — use context.WithTimeout to limit the execution time of the database query.

  2. Connection pool — properly configure the connection pool to avoid deadlocks and delays.

  3. Error handling — correctly handle timeout errors and return understandable responses to the client.

Example of using a context with timeout:

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 waiting time for the response from the database.