本文整理汇总了Golang中code/google/com/p/log4go.Error函数的典型用法代码示例。如果您正苦于以下问题:Golang Error函数的具体用法?Golang Error怎么用?Golang Error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getFoodPrice
func (self *FoodPriceService) getFoodPrice(username string, args []string) (string, error) {
if args == nil || len(args) == 0 {
return "", errors.New("缺少参数!")
}
cityOrDistrict := args[0]
cityCode := self.getCityCode(cityOrDistrict)
if len(cityCode) > 0 {
foodPriceMessage, err := self.getCityFoodPrice(cityCode)
if err != nil {
l4g.Error("Get city food price failed: %v", err)
return "", errors.New("获取数据失败!")
}
return foodPriceMessage, nil
}
districtCode := self.getDistrictCode(cityOrDistrict)
if len(districtCode) > 0 {
foodPriceMessage, err := self.getDistrictFoodPrice(districtCode)
if err != nil {
l4g.Error("Get district food price failed: %v", err)
return "", errors.New("获取数据失败!")
}
return foodPriceMessage, nil
}
return "", errors.New("不支持该城市或地区的菜价查询!")
}
示例2: LoadConfig
// LoadConfig will try to search around for the corresponding config file.
// It will search /tmp/fileName then attempt ./config/fileName,
// then ../config/fileName and last it will look at fileName
func LoadConfig(fileName string) {
fileName = findConfigFile(fileName)
l4g.Info("Loading config file at " + fileName)
file, err := os.Open(fileName)
if err != nil {
panic("Error opening config file=" + fileName + ", err=" + err.Error())
}
decoder := json.NewDecoder(file)
config := Config{}
err = decoder.Decode(&config)
if err != nil {
panic("Error decoding configuration " + err.Error())
}
// Check for a valid email for feedback, if not then do [email protected]
if _, err := mail.ParseAddress(config.EmailSettings.FeedbackEmail); err != nil {
config.EmailSettings.FeedbackEmail = "[email protected]"
l4g.Error("Misconfigured feedback email setting: %s", config.EmailSettings.FeedbackEmail)
}
configureLog(config.LogSettings)
Cfg = &config
SanitizeOptions = getSanitizeOptions()
// Validates our mail settings
if err := CheckMailSettings(); err != nil {
l4g.Error("Email settings are not valid err=%v", err)
}
}
示例3: handleConnection
func (self *ProtobufServer) handleConnection(conn net.Conn) {
log.Info("ProtobufServer: client connected: %s", conn.RemoteAddr().String())
message := make([]byte, 0, MAX_REQUEST_SIZE)
buff := bytes.NewBuffer(message)
var messageSizeU uint32
for {
err := binary.Read(conn, binary.LittleEndian, &messageSizeU)
if err != nil {
log.Error("Error reading from connection (%s): %s", conn.RemoteAddr().String(), err)
self.connectionMapLock.Lock()
delete(self.connectionMap, conn)
self.connectionMapLock.Unlock()
conn.Close()
return
}
messageSize := int64(messageSizeU)
if messageSize > MAX_REQUEST_SIZE {
err = self.handleRequestTooLarge(conn, messageSize, buff)
} else {
err = self.handleRequest(conn, messageSize, buff)
}
if err != nil {
log.Error("Error, closing connection: %s", err)
self.connectionMapLock.Lock()
delete(self.connectionMap, conn)
self.connectionMapLock.Unlock()
conn.Close()
return
}
buff.Reset()
}
}
示例4: ListenAndServe
/**
** subscribe the all connected queues from queue server
** and to be connect the channel and serve the messages to handlers
**/
func (self *QueueServer) ListenAndServe() {
factor, err := amqp.Factory()
if err != nil {
log.Error("Failed to get the queue instance: %s", err)
}
pubsub, err := factor.Get(self.ListenAddress)
if err != nil {
log.Error("Failed to get the queue instance: %s", err)
}
//res := &global.Message{}
msgChan, _ := pubsub.Sub()
for msg := range msgChan {
log.Info(" [x] %q", msg)
queue1, _ := config.GetString("name")
if self.ListenAddress == queue1 {
coordinator.Handler(msg)
}
}
log.Info("Handling message %v", msgChan)
self.chann = msgChan
}
示例5: acceptTCP
// Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks; the caller typically
// invokes it in a go statement.
func acceptTCP(server *Server, lis *net.TCPListener) {
var (
conn *net.TCPConn
err error
r int
)
for {
if conn, err = lis.AcceptTCP(); err != nil {
// if listener close then return
log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
return
}
if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
log.Error("conn.SetKeepAlive() error(%v)", err)
return
}
if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
log.Error("conn.SetReadBuffer() error(%v)", err)
return
}
if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
log.Error("conn.SetWriteBuffer() error(%v)", err)
return
}
go serveTCP(server, conn, r)
if r++; r == maxInt {
r = 0
}
}
}
示例6: CreateUser
func CreateUser(c *Context, team *model.Team, user *model.User) *model.User {
if !utils.Cfg.TeamSettings.EnableUserCreation {
c.Err = model.NewAppError("CreateUser", "User creation has been disabled. Please ask your systems administrator for details.", "")
return nil
}
channelRole := ""
if team.Email == user.Email {
user.Roles = model.ROLE_TEAM_ADMIN
channelRole = model.CHANNEL_ROLE_ADMIN
// Below is a speical case where the first user in the entire
// system is granted the system_admin role instead of admin
if result := <-Srv.Store.User().GetTotalUsersCount(); result.Err != nil {
c.Err = result.Err
return nil
} else {
count := result.Data.(int64)
if count <= 0 {
user.Roles = model.ROLE_SYSTEM_ADMIN
}
}
} else {
user.Roles = ""
}
user.MakeNonNil()
if result := <-Srv.Store.User().Save(user); result.Err != nil {
c.Err = result.Err
l4g.Error("Couldn't save the user err=%v", result.Err)
return nil
} else {
ruser := result.Data.(*model.User)
// Soft error if there is an issue joining the default channels
if err := JoinDefaultChannels(ruser, channelRole); err != nil {
l4g.Error("Encountered an issue joining default channels user_id=%s, team_id=%s, err=%v", ruser.Id, ruser.TeamId, err)
}
addDirectChannelsAndForget(ruser)
if user.EmailVerified {
if cresult := <-Srv.Store.User().VerifyEmail(ruser.Id); cresult.Err != nil {
l4g.Error("Failed to set email verified err=%v", cresult.Err)
}
}
ruser.Sanitize(map[string]bool{})
// This message goes to every channel, so the channelId is irrelevant
message := model.NewMessage(team.Id, "", ruser.Id, model.ACTION_NEW_USER)
PublishAndForget(message)
return ruser
}
}
示例7: PostUpdateChannelHeaderMessageAndForget
func PostUpdateChannelHeaderMessageAndForget(c *Context, channelId string, oldChannelHeader, newChannelHeader string) {
go func() {
uc := Srv.Store.User().Get(c.Session.UserId)
if uresult := <-uc; uresult.Err != nil {
l4g.Error("Failed to retrieve user while trying to save update channel header message %v", uresult.Err)
return
} else {
user := uresult.Data.(*model.User)
var message string
if oldChannelHeader == "" {
message = fmt.Sprintf("%s updated the channel header to: %s", user.Username, newChannelHeader)
} else if newChannelHeader == "" {
message = fmt.Sprintf("%s removed the channel header (was: %s)", user.Username, oldChannelHeader)
} else {
message = fmt.Sprintf("%s updated the channel header from: %s to: %s", user.Username, oldChannelHeader, newChannelHeader)
}
post := &model.Post{
ChannelId: channelId,
Message: message,
Type: model.POST_HEADER_CHANGE,
}
if _, err := CreatePost(c, post, false); err != nil {
l4g.Error("Failed to post join/leave message %v", err)
}
}
}()
}
示例8: InitWebsocket
func InitWebsocket() (err error) {
var (
listener *net.TCPListener
addr *net.TCPAddr
httpServeMux = http.NewServeMux()
)
httpServeMux.Handle("/sub", websocket.Handler(serveWebsocket))
for _, bind := range Conf.WebsocketBind {
if addr, err = net.ResolveTCPAddr("tcp4", bind); err != nil {
log.Error("net.ResolveTCPAddr(\"tcp4\", \"%s\") error(%v)", bind, err)
return
}
if listener, err = net.ListenTCP("tcp4", addr); err != nil {
log.Error("net.ListenTCP(\"tcp4\", \"%s\") error(%v)", bind, err)
return
}
server := &http.Server{Handler: httpServeMux}
log.Debug("start websocket listen: \"%s\"", bind)
go func() {
if err = server.Serve(listener); err != nil {
log.Error("server.Serve(\"%s\") error(%v)", bind, err)
panic(err)
}
}()
}
return
}
示例9: RegisterTemp
// RegisterTmp create a ephemeral node, and watch it, if node droped then send a SIGQUIT to self.
func RegisterTemp(conn *zk.Conn, fpath string, data []byte) error {
tpath, err := conn.Create(path.Join(fpath)+"/", data, zk.FlagEphemeral|zk.FlagSequence, zk.WorldACL(zk.PermAll))
if err != nil {
log.Error("conn.Create(\"%s\", \"%s\", zk.FlagEphemeral|zk.FlagSequence) error(%v)", fpath, string(data), err)
return err
}
log.Debug("create a zookeeper node:%s", tpath)
// watch self
go func() {
for {
log.Info("zk path: \"%s\" set a watch", tpath)
exist, _, watch, err := conn.ExistsW(tpath)
if err != nil {
log.Error("zk.ExistsW(\"%s\") error(%v)", tpath, err)
log.Warn("zk path: \"%s\" set watch failed, kill itself", tpath)
killSelf()
return
}
if !exist {
log.Warn("zk path: \"%s\" not exist, kill itself", tpath)
killSelf()
return
}
event := <-watch
log.Info("zk path: \"%s\" receive a event %v", tpath, event)
}
}()
return nil
}
示例10: NewMySQLStorage
// NewMySQLStorage initialize mysql pool and consistency hash ring.
func NewMySQLStorage() *MySQLStorage {
var (
err error
w int
nw []string
db *sql.DB
)
dbPool := make(map[string]*sql.DB)
ring := ketama.NewRing(ketamaBase)
for n, source := range Conf.MySQLSource {
nw = strings.Split(n, ":")
if len(nw) != 2 {
err = errors.New("node config error, it's nodeN:W")
log.Error("strings.Split(\"%s\", :) failed (%v)", n, err)
panic(err)
}
w, err = strconv.Atoi(nw[1])
if err != nil {
log.Error("strconv.Atoi(\"%s\") failed (%v)", nw[1], err)
panic(err)
}
db, err = sql.Open("mysql", source)
if err != nil {
log.Error("sql.Open(\"mysql\", %s) failed (%v)", source, err)
panic(err)
}
dbPool[nw[0]] = db
ring.AddNode(nw[0], w)
}
ring.Bake()
s := &MySQLStorage{pool: dbPool, ring: ring}
go s.clean()
return s
}
示例11: handleTcpConn
// hanleTCPConn handle a long live tcp connection.
func handleTcpConn(conn net.Conn, readerChan chan *bufio.Reader) {
addr := conn.RemoteAddr().String()
log.Debug("<%s> handleTcpConn routine start", addr)
reader := newBufioReader(readerChan, conn)
if args, err := parseCmd(reader); err == nil {
// return buffer bufio.Reader
putBufioReader(readerChan, reader)
switch args[0] {
case CmdSubscribe:
subscribeTcpHandle(conn, args[1:])
default:
conn.Write(ParamErrorReply)
log.Warn("<%s> unknown cmd \"%s\"", addr, args[0])
}
} else {
// return buffer bufio.Reader
putBufioReader(readerChan, reader)
log.Error("<%s> parseCmd() error(%v)", addr, err)
}
// close the connection
if err := conn.Close(); err != nil {
log.Error("<%s> conn.Close() error(%v)", addr, err)
}
log.Debug("<%s> handleTcpConn routine stop", addr)
}
示例12: GetPrivate
// GetPrivate implements the Storage GetPrivate method.
func (s *MySQLStorage) GetPrivate(key string, mid int64) ([]*myrpc.Message, error) {
db := s.getConn(key)
if db == nil {
return nil, ErrNoMySQLConn
}
now := time.Now().Unix()
rows, err := db.Query(getPrivateMsgSQL, key, mid)
if err != nil {
log.Error("db.Query(\"%s\",\"%s\",%d,now) failed (%v)", getPrivateMsgSQL, key, mid, err)
return nil, err
}
msgs := []*myrpc.Message{}
for rows.Next() {
expire := int64(0)
cmid := int64(0)
msg := []byte{}
if err := rows.Scan(&cmid, &expire, &msg); err != nil {
log.Error("rows.Scan() failed (%v)", err)
return nil, err
}
if now > expire {
log.Warn("user_key: \"%s\" mid: %d expired", key, cmid)
continue
}
msgs = append(msgs, &myrpc.Message{MsgId: cmid, GroupId: myrpc.PrivateGroupId, Msg: json.RawMessage(msg)})
}
return msgs, nil
}
示例13: unsubFoodPrice
func (self *FoodPriceService) unsubFoodPrice(username string, args []string) (string, error) {
if args == nil || len(args) == 0 {
return "", errors.New("缺少参数!")
}
cityOrDistrict := self.getCityOrDistrictCode(args[0])
if len(cityOrDistrict) == 0 {
return "", errors.New("不支持订阅该城市或地区的菜价!")
}
userSubEntity, err := self.dbHelper.GetUserSub(username, cityOrDistrict)
if err != nil {
l4g.Error("GetUserSub error in unsubscribe food price: username: %s, error: %v", username, err)
return "", errors.New("退订失败!")
}
if userSubEntity != nil {
userSubEntity.SubStatus = 0
updateError := self.dbHelper.UpdateUserSub(userSubEntity)
if updateError != nil {
l4g.Error("UpdateUserSub error in unsubscribe food price: username: %s, error: %v", username, err)
return "", errors.New("退订失败!")
}
} else {
return "未订阅过该城市的空气质量信息!", nil
}
return "退订成功!", nil
}
示例14: subFoodPrice
func (self *FoodPriceService) subFoodPrice(username string, args []string) (string, error) {
if args == nil || len(args) == 0 {
return "", errors.New("缺少参数!")
}
cityOrDistrict := self.getCityOrDistrictCode(args[0])
if len(cityOrDistrict) == 0 {
return "", errors.New("不支持订阅该城市或地区的菜价!")
}
userSubEntity, err := self.dbHelper.GetUserSub(username, cityOrDistrict)
if err != nil {
l4g.Error("GetUserSub error in subscribe food price: username: %s, error: %v", username, err)
return "", errors.New("订阅失败!")
}
if userSubEntity == nil {
userSubEntity = &UserSubEntity{}
userSubEntity.Username = username
userSubEntity.CityOrDistrict = cityOrDistrict
userSubEntity.SubStatus = 1
addError := self.dbHelper.AddUserSub(userSubEntity)
if addError != nil {
l4g.Error("AddUserSub error in subscribe food price: username: %s, error: %v", username, err)
return "", errors.New("订阅失败!")
}
} else {
userSubEntity.SubStatus = 1
updateError := self.dbHelper.UpdateUserSub(userSubEntity)
if updateError != nil {
l4g.Error("UpdateUserSub error in subscribe food price: username: %s, error: %v", username, err)
return "", errors.New("订阅失败!")
}
}
return "订阅成功!", nil
}
示例15: Push
// Push push a message to a specified sub key, must goroutine safe.
func Push(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method Not Allowed", 405)
return
}
body := ""
res := map[string]interface{}{"ret": OK}
defer retPWrite(w, r, res, &body, time.Now())
// param
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
res["ret"] = InternalErr
log.Error("ioutil.ReadAll() failed (%v)", err)
return
}
params := r.URL.Query()
key := params.Get("key")
log.Debug("push key: \"%s\"", key)
bucket := DefaultServer.Bucket(key)
if channel := bucket.Get(key); channel != nil {
// padding let caller do
if err = channel.PushMsg(1, OP_SEND_SMS_REPLY, bodyBytes); err != nil {
res["ret"] = InternalErr
log.Error("channel.PushMsg() error(%v)", err)
return
}
}
res["ret"] = OK
return
}