Golang *pq.Error handler for postgres

Sat, Nov 12, 2022 One-minute read

Golang *pq.Error handler for postgres

Since switching over to sqlc I no longer have access to the models. This means custom error message returns are not possible (at least to my knowledge). This caught me out as a duplicate key error which used to get trapped was slipping through my validation in Mudmap.

Here’s how to catch postgres errors using github.com/lib/pq.

Note: apparently pgx has much better handling for this out of the box.

// from inside a Mudmap handler.
dd, err := app.Db.DeviceOrgInsert(context.Background(), orgArgs)
		if err != nil {
      // here we crate a variable of the pq.Error type
			var pgErr *pq.Error
			switch {
      // Using errors.As we inspect the error type
			case errors.As(err, &pgErr):
        // I chose to be explicit and call .Name() rather than
        // case over the Code which in this case is 25302 or something
				switch pgErr.Code.Name() {
				case "unique_violation":
					v.AddError("devices_host_address_key", "a device with this host address already exists")
					app.failedValidationResponse(w, r, v.Errors)
				default:
					app.Logger.Error().Err(err).Msg("pg-error")
					app.serverErrorResponse(w, r, err)
				}
				return
      }
    return
  }

Tags:

#go #postgres #errors