Declarative Programming – Error Messages

אם יש איזה בעיה בהבאת הנתונים, אנחנו צריכים להציג חיווי למשתמש. מכיוון שאנחנו לא משתמשים ב-subscribe אנחנו גם לא משתמשים בהודעות השגיאה שהפעולה נותנת לנו. איך תופסים את השגיאות?

catchError Operator

על מנת לתפוס את השגיאות נשתמש באופרטור catchError. אם תהיה שגיאה האופרטור יתפוס אותה.

כרגע זאת הדרך שבה אנחנו מביאים את הפוסטים.

קובץ declarative-posts.service.cs

posts$ = this.http.get<Post[]>(`${this.baseUrl}/posts`);

לקוד הזה נוסיף את האופרטור catchError ונשלח את הטיפול בשגיאות לפונקציה handleError שניצור.

posts$ = this.http.get<Post[]>(`${this.baseUrl}/posts`)
    .pipe(catchError(this.handleError));

handleError(error: Error){
  return throwError(() => {
    return "Error in program";
  });
}

את השגיאה הזאת אנחנו רוצים לתפוס בקומפוננטה. בקומפוננטה נכים משתנה שיקבל את השגיאה ונחבר אותה למשתנה שמכיל את הפוסטים.

קובץ directive-posts.component.ts

errorMessage = '';

posts$ = this.postService.postsWithCategory$.pipe(catchError((error) => {
  this.errorMessage = error;
  return EMPTY;
}));

את אותה הפעולה נעשה גם לשאר משתני המידע שיש לנו.

את השגיאה אנחנו רוצים להציג למשתמש. נציג למשל שגיאה בעמוד הפוסטים single-post.

צעד ראשון הוספה של תפיסת השגיאה בקומפוננטה.

קובץ single-post.component.ts

errorMessage = '';
  
post$ = this.postService.post$.pipe(catchError((error) => {
    this.errorMessage = error;
    return EMPTY;
}));

נכניס את השגיאה למסך התצוגה.

קובץ single-post.component.html

<div class="row" *ngIf="errorMessage">
  <div class="col-md-12">
    <div class="alert alert-danger">{{ errorMessage }}</div>
  </div>
</div>

כדי לעקוב אחרי השגיאות, אפשר להפוך את השגיאה ל-subject.

קובץ single-post.component.ts

errorMessageSubject$ = new BehaviorSubject<string>('');
errorMessageAction$  = this.errorMessageSubject$.asObservable();

post$ = this.postService.post$.pipe(catchError((error) => {
  this.errorMessageSubject$.next(error);
  return EMPTY;
}));

קובץ single-post.component.html

<div class="row" *ngIf="errorMessageAction$ | async as errorMessage">
  <div class="col-md-12">
    <div class="alert alert-danger">{{ errorMessage }}</div>
  </div>
</div>

ניווט במאמר

מאמרים אחרונים

Weekly Tutorial