arekkusu6

sqlc error handler

Oct 28th, 2025 (edited)
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.37 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "database/sql"
  6.     "errors"
  7.     "fmt"
  8.     "gotesting/db"
  9.     "log"
  10.     "net/http"
  11.  
  12.     "github.com/mattn/go-sqlite3"
  13. )
  14.  
  15.  
  16. type query[RES, ARG any] func(context.Context, ARG) (RES, error)
  17.  
  18. func RunQuery[RES, ARG any](ctx context.Context, query query[RES, ARG], arg ARG) (RES, int, error) {
  19.     res, err :=  query(ctx, arg)
  20.  
  21.     if err != nil {
  22.         switch true {
  23.             case ctx.Err() == context.DeadlineExceeded:
  24.                 return res, http.StatusGatewayTimeout, errors.New("query took too long")
  25.  
  26.             case errors.Is(err, sql.ErrNoRows):
  27.                 return res, http.StatusNotFound, errors.New("datas not found")
  28.  
  29.             case errors.As(err, &sqlite3.Error{ExtendedCode: sqlite3.ErrConstraintUnique}):
  30.                 return res, http.StatusBadRequest, errors.New("one or more fields already exists in the database")
  31.  
  32.             case errors.As(err, &sqlite3.Error{ExtendedCode: sqlite3.ErrConstraintCheck}):
  33.                 return res, http.StatusBadRequest, errors.New("one or more fields in the query are invalid")
  34.  
  35.             default:
  36.                 log.Println(err)
  37.                 return res, http.StatusInternalServerError, errors.New("database error")
  38.         }
  39.     }
  40.  
  41.     return res, 0, nil
  42. }
  43.  
  44.  
  45. func main() {
  46.     db.InitDB()
  47.  
  48.  
  49.     messages, status, err := RunQuery(context.Background(), db.Query.GetYourMessages, db.GetYourMessagesParams{
  50.         UserID: 1,
  51.         ChatID: 1,
  52.     })
  53.  
  54.     if err != nil {
  55.         log.Fatal(status, err)
  56.     }
  57.  
  58.     fmt.Println(messages)
  59. }
Advertisement
Add Comment
Please, Sign In to add comment