programing

각도 시도 캐치 vs 포수 오류

prostudy 2022. 3. 15. 20:49
반응형

각도 시도 캐치 vs 포수 오류

각 프로젝트의 경우 모든 api 경로(검색 경로) 목록을 포함하는 url을 받는다.내 애플리케이션에서 검색 경로를 호출하여 결과를 목록에 저장하고자 한다.내 코드:

discover(): Observable<ApiLink[]> {
    if (this.links) {
      return of(this.links);
    }
    try {
      console.log('calling :', URL);
      return this.http.get<{links: ApiLink[]}>(URL, {headers: this.headers}).pipe(
        map(response => {
          this.links = response.links;
          return this.links;
        }),
        catchError(some_error => {
          console.log('error ', some_error);
          throw new Error('failed to discover the api.');
        }),
      );
    } catch (e) {
      console.log('api discover failed ', e);
      throw new Error('failed to discover the api.');
    }
  }

내 질문은 그것이 언제 catchError로 가고 언제 잡을 것인가이다.통화가 완료되었지만 오류 500을 반환하는 경우, 포수 오류는 캐치 에러인가, 유효한 응답인가(통화가 제대로 작동되었는가)?그리고 호출 방법은 가능한 오류를 어떻게 처리해야 하는가.포수 오류로 전화할 때 정확한가?

  // we give a string that relates to a path e.g. 'user' returns someurl.com/api/users
  url(rel: string, params?: object): Observable<string> {
    return this.discover().pipe(
      map(links => {
        const link = links.find(item => item.rel === rel);
        if (link) {
          return link.href;
        } else {
          throw new Error(`IXapi entry "${rel}" was not found.`);
        }
      }),
      catchError( errormessage => {
        console.log('error inside url ', rel, ' error:', errormessage);
        throw errormessage;
      })
    );
  }

아니면 트라이 캐치(try catch)로 해야 한다.

  url(rel: string, params?: object): Observable<string> {
    console.log('url: ', rel);
    try{
    return this.discover().pipe(
     // do stuff
    );
    }catch(e)
     {
       console.log('do some stuff because we have an error');           
       throw e;
     }
  }

간단히 말해서, 시도/캐치 대 포수 오류를 언제 사용해야 하며, 호출 방법에서 포수 오류/시도 캐치에 던져진 오류를 어떻게 잡아야 하는가?

동기식 프로그래밍에서 우리는 던져지는 오류를 잡기 위해 전통적인 시도 캐치 블록을 사용한다.

try {
   // synchronous operation
   const httpResponse =  getHttpResponseSync('/api/getUsers');
}
catch(error) {
    // handle error
}

그러나 HTTP 요청과 같은 그것의 비동기 프로그래밍이 우리는 이 시도 캐치 블록에 의존할 수 없다.

그래서 Rxjs는 이 catchError를 Observable 입력을 받아들이고 Output Observable을 출력하는 함수를 제공한다.

이 기능은 방금 침식된 하천에 대해 관측 가능한 대체물이 될 관측 가능을 반환할 것으로 예상된다.

첫 번째 질문대로!http.가 비동기식으로 만드는 관찰 가능한 정보를 얻기 때문에 항상 catchError로 이동한다.

https://www.intertech.com/Blog/angular-best-practice-rxjs-error-handling/을 참조하십시오.

Js 코드의 일반 캐칭 오류에 대해 캐치 시도

이것처럼.

try {
  adddlert("Welcome guest!");
}
catch(err) {
  document.getElementById("demo").innerHTML = err.message;
}

캐치오러는 관측 가능한 오류 캐치에 사용된다.

import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));

참조URL: https://stackoverflow.com/questions/59245729/angular-try-catch-vs-catcherror

반응형