1.java中有try。。。catch 捕获异常并handle,golang中是什么机制?
主要有三个概念:defer 使用recover前提声明 recover捕获异常 panic异常
/** 捕获异常 **/ func DeferFunc(o *beego.Controller) { if e := recover(); e != nil { logs.Error(" 错误 %s\r\n", e) Return(o, nil, e) } }
/** 抛出异常 **/ func (it *EvtAccidentController) Add() { DeferFunc(&it.Controller) accident := new(model.EvtAccident) data := it.Ctx.Input.RequestBody if data != nil { if err := json.Unmarshal(data, &accident); err != nil { panic(err) } validations := accident.Validation(nil) if validations != nil { Return(&it.Controller, validations, errors.New("验证没通过")) } else { i, e := evtAccidentService.EvtAccidentInsert(accident) Return(&it.Controller, i, e) } } else { panic(errors.New("json数据不存在")) } }