golang中的异常如何捕获?


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数据不存在"))
	}
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM