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