golang 웹 프레임 워 크 utron 의 이상 통일 처리

1914 단어 Golang
골 랑 은 함수 가 Error 로 돌아 가 는 방식 을 제공 하여 함수 호출 이 잘못 되 었 는 지 안전하게 검사 하 는 데 도움 을 주 었 지만, 일부 실행 중인 패 닉 은 잡 을 수 없 었 습 니 다.우 리 는 Spring 의 @ Controller Advice 주해 류 처럼 안에 있 는 @ Exception Handler 주 해 를 실현 하 는 방법 을 실현 하면 모든 Exception 이 Unchecked Exception 을 포함 하 는 것 을 잡 을 수 있 기 를 바 랍 니 다.
debug 를 통 해 우 리 는 routes. go 파일 을 찾 았 습 니 다. 안의 wrapController () 방법 은 http 요청 의 입 구 를 처리 하 는 것 입 니 다. 원래 코드 는 다음 과 같 습 니 다.
// wrapController wraps a controller ctrl with method fn, and returns http.HandleFunc
func (r *Router) wrapController(ctx *base.Context, fn string, ctrl controller.Controller) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		r.handleController(ctx, fn, ctrl)
	}
}

이곳 의 handle Controller () 방법 은 실현 되 었 습 니 다. 좋 은 처리 전략 이 없 으 며 http Status 500 만 되 돌려 줍 니 다.
// executes the method fn on Controller ctrl, it sets context.
func (r *Router) handleController(ctx *base.Context, fn string, ctrl controller.Controller) {
	ctrl.New(ctx)
	// execute the method
	// TODO: better error handling?
	if x := ita.New(ctrl).Call(fn); x.Error() != nil {
		ctx.Set(http.StatusInternalServerError)
		_, _ = ctx.Write([]byte(x.Error().Error()))
		ctx.TextPlain()
		_ = ctx.Commit()
		return
	}
	err := ctx.Commit()
	if err != nil {
		//TODO:  Log error
		ctx.Log.Errors("=============
%s===========
",err.Error()) } }

우 리 는 앞 뒤 가 분리 되 어 있 습 니 다. 전단 은 통 일 된 형식의 JSON 을 받 기 를 원 합 니 다. 형식 은 다음 과 같 습 니 다.
4. 567913. 우리 의 방법 도 간단 합 니 다. 바로 wrapController () 에 defer 함 수 를 추가 하여 handle Controller () 에서 던 진 모든 이상 을 캡 처 하 는 것 입 니 다. 코드 는 다음 과 같 습 니 다.
{"Code":"FAIL","Msg":"We caught a panic","Data":"invalid memory address or nil pointer dereference"}

ResultJSon 은 우리 가 정의 한 Struct 로 Code, Msg, Data 세 가지 속성 을 포함 하고 있 습 니 다.

좋은 웹페이지 즐겨찾기