2017-03-29 1 views
1

그래서 예외 처리 방법에 대한 패턴을 찾고 있습니다. 특히 웹 API 컨트롤러에서 예외 메시지를 클라이언트에 전달할 수 있어야합니다.웹 API와 각도 2 클라이언트 간의 오류 처리

는 클라이언트가

this.msgs = []; 
let xhr = new XMLHttpRequest(), 
formData = new FormData(); 


for(let i = 0; i < this.files.length; i++) { 
    formData.append(this.name, this.files[i], this.files[i].name); 
} 

xhr.upload.addEventListener('progress', (e: ProgressEvent) => { 
    if(e.lengthComputable) { 
     this.progress = Math.round((e.loaded * 100)/e.total); 
    } 
    }, false); 

xhr.onreadystatechange =() => { 
    if(xhr.readyState == 4) { 
     this.progress = 0; 

     if(xhr.status == 200) 
      this.onUpload.emit({xhr: xhr, files: this.files}); 
     else 
      this.onError.emit({xhr: xhr, files: this.files}); 

     this.clear(); 
    } 
}; 

xhr.open('POST', this.url, true); 
xhr.send(formData); 

나의 현재 콜백 함수와 API 에 대한 호출을 다루는 타사 라이브러리를 사용

errorComplete(event: any) { 
    console.log("upload error"); 
} 

통지 입니다 해당 오류에 대한 라이브러리 단지 XMLHttpRequest를 래핑하고 콜백 함수에 전달합니다.

이 예기치 않은 예외

을 시뮬레이션하는 것입니다

throw new Exception("This is a test message"); 

현재는 XMLHttpRequest의 리턴 코드는 500이다 다음과 같이

그래서 컨트롤러에서 I는 테스트 라인을 만든 텍스트는 HTML입니다 예외가 발생할 때 .Net 생성합니다.

예 내 컨트롤러의 메서드는 try-catch에서 래퍼가 필요하지만 클라이언트에게 오류 메시지를 보낼 수 있도록 어떤 코드를 catch에 넣을 지 확신하지 못하고 처리 할 수 ​​있습니다. 신청서를 철회하십시오.

내가보고있는 현재의 유스 케이스는 사용자가 파일을 시스템에 업로드하지만 이미 시스템에 지정된 이름의 파일이 있습니다. 파일 이름 바꾸기는 옵션이 아닙니다! 시스템에 이미 그 이름의 파일이 있음을 사용자에게 알려야합니다.

Google에서 처리 할 수 ​​있도록 메시지를 다시 전달하는 방법을 공개하지 않았습니다.

+0

컨트롤러에서 try catch를 사용하지 마십시오. ExceptionHandler 파생 클래스를 통해 교차 절단 문제를 사용합니다. 해당 클래스에서 오류 코드와 본문을 반환하도록하십시오. 보통 500 내부 서버 오류. 본문은 앱과 관련된 맞춤 세부 정보를 가질 수 있습니다. – Nkosi

답변

1

감사합니다. Nkosi- 귀하의 의견은 올바른 방향으로 나를 잡았습니다. 미들웨어를 구현했습니다. 사람이 솔루션으로 문제를보고하는 경우

public class UIExceptionHandler 
{ 
    RequestDelegate _next; 
    public UIExceptionHandler(RequestDelegate next) 
    { 
     this._next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     try 
     { 
      await this._next(context); 
     } 
     catch (Exception x) 
     { 
      if (!context.Response.HasStarted) 
      { 
       context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; 
       context.Response.Headers["Message"] = x.Message; 
      } 
     } 
    } 
} 

public static class UIExcetionHandlerExtensions 
{ 
    public static IApplicationBuilder UseUIExceptionHandler(this IApplicationBuilder builder) 
    { 
     return builder.UseMiddleware<UIExceptionHandler>(); 
    } 
} 

과 시작의 구성 방법에

app.UseUIExceptionHandler(); 

다음 클라이언트에서 내가

errorComplete(event: any) { 
    var errorMessage = event.xhr.getResponseHeader('Message'); 
    console.log(errorMessage); 
} 

을 할 수있는 날

을 알려 주시기 바랍니다