Angular Error Handling: จัดการ Error อย่างมืออาชีพ
#angular12 เม.ย. 2569
ทำไม Error Handling ถึงสำคัญ
การจัดการ error ที่ดีช่วยให้ user experience ดีขึ้น และช่วย debug ได้ง่ายขึ้น
Global Error Handler
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: Error) {
console.error('Global Error:', error);
// ส่งไปยัง error tracking service เช่น Sentry
// Sentry.captureException(error);
}
}
// main.ts
bootstrapApplication(AppComponent, {
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler }
]
});
HTTP Error Interceptor
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
switch (error.status) {
case 401:
// redirect to login
inject(Router).navigate(['/login']);
break;
case 403:
inject(Router).navigate(['/forbidden']);
break;
case 404:
inject(Router).navigate(['/not-found']);
break;
case 500:
inject(NotificationService).error('เซิร์ฟเวอร์มีปัญหา');
break;
}
return throwError(() => error);
})
);
};
Error Boundary Component
@Component({
selector: 'app-error-boundary',
template: `
@if (hasError()) {
<div class="error-state">
<h2>เกิดข้อผิดพลาด</h2>
<button (click)="retry()">ลองใหม่</button>
</div>
} @else {
<ng-content />
}
`
})
export class ErrorBoundaryComponent {
hasError = signal(false);
private errorHandler = inject(ErrorHandler);
retry() {
this.hasError.set(false);
}
}
Retry Logic
import { retry, catchError } from 'rxjs/operators';
getData() {
return this.http.get('/api/data').pipe(
retry({ count: 3, delay: 1000 }),
catchError(err => {
this.error.set('โหลดข้อมูลไม่สำเร็จ');
return throwError(() => err);
})
);
}
สรุป
การจัดการ error ที่ดีควรมีทั้ง Global Error Handler, HTTP Interceptor และ retry logic ช่วยให้ app มีความ robust มากขึ้นครับ