본문 바로가기

.Net

[c#] Globel Exception Deligation Handler

    // 참조
    // https://stackoverflow.com/questions/13013973/asp-net-web-api-default-error-messages
    // DelegatingHandler : 내부 핸들러라고 하는 다른 핸들러에 HTTP 응답 메시지 처리를 위임하는 HTTP 핸들러의 유형입니다.
    //                     https://learn.microsoft.com/ko-kr/dotnet/api/system.net.http.delegatinghandler?view=netframework-4.8
    //                     http://www.egocube.pe.kr/Translation/Content/asp-net-web-api/201309040001
    public class GlobalExceptionDeligatingHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
        		HttpRequestMessage request, CancellationToken cancellationToken
            )
        {
            string log_key = Const.LOGKey;

            return base.SendAsync(request, cancellationToken)
            		   .ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
            {
                HttpResponseMessage response = responseToCompleteTask.Result;
                HttpError error = null;

                if ((!response.IsSuccessStatusCode) && (response.TryGetContentValue(out error)))
                {
                    // 로그에 상세한 에러 내용 기록
                    string logMsg = string.Format(
                        "[GlobalException]\n[{0}]{1}{2}"
                        , log_key
                        , !string.IsNullOrWhiteSpace(error.Message) 
                             ? " ## " + error.Message + "\n" : ""
                        , !string.IsNullOrWhiteSpace(error.ExceptionMessage) 
                             ? " ## " + "[" + error.ExceptionType + "]" + error.ExceptionMessage + "\n" : ""
                    );
                    
                    LogManager.WirteLog(logMsg);

                    // 공통 리턴 객체를 생성하여 에러 메세지를 등록
                    string returnMsg = string.Format("[GlobalException]\n[{0}]{1}{2}"
                        , log_key
                        , (!string.IsNullOrWhiteSpace(error.ExceptionMessage) 
                              ? "[" + error.ExceptionType + "]" + error.ExceptionMessage + "\n" : "")
                        , (!string.IsNullOrWhiteSpace(error.MessageDetail) 
                              ? error.MessageDetail + "\n" : "")
                    );
                    
                    ResultTable rtn = new ResultTable();
                    rtn.status = Result.Failure(returnMsg);
                    rtn.SetPath(request.RequestUri.AbsolutePath);
                    
                    // response.Content 값을 공통 리턴 객체로 리턴합니다.
                    response.Content = new ObjectContent(
                        typeof(ResultTable)
                      , rtn
                      , new JsonMediaTypeFormatter()
                    );
                }

                return response;
            });
        }
    }