สารบัญเนื้อหา
- สร้าง Helper เพื่อช่วยในการจัดการกับ Error Message ใน API
- กำหนดให้ใช้ Helper เพื่อจัดการกับ Error Message ใน Production ใน API
- จัดการกับ Error ใน Angular
1. สร้าง Helper เพื่อช่วยในการจัดการกับ Error Message ใน API
เพิ่ม Extensions Helper ใน API เพื่อเป็นตัวช่วยในการส่ง Error Message

2. กำหนดให้ใช้ Helper เพื่อจัดการกับ Error Message ใน Production ใน API
ปรับปรุง Configure ใน Startup.cs ให้แสกง Error Message กรณีระบบขึ้น Production

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
ลองกำหนดให้ระบบรันแบบ Production แล้วลองรันเพื่อทดสอบการแสดงผล Error

ทดสอบรันและส่งข้อมูลให้มี Error โดยใช้ Postman
3. จัดการกับ Error ใน Angular
สร้าง Service error.interceptor.ts ใน _services

import { Injectable, ApplicationModule } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError(error => {
if (error.status === 401) {
return throwError(error.statusText);
}
if (error instanceof HttpErrorResponse) {
const applicationError = error.headers.get('Application-Error');
if (applicationError) {
return throwError(applicationError);
}
const serverError = error.error;
let modalStateErrors = '';
if (serverError.errors && typeof serverError.errors === 'object') {
for (const key in serverError.errors) {
if (serverError.errors[key]) {
modalStateErrors += serverError.errors[key] + '\n';
}
}
}
return throwError(modalStateErrors || serverError || 'Server Error');
}
})
);
}
}
export const ErrorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}
เพิ่ม Providers ใน app.module.ts

ทดสอบรัน จะพบว่า Error Message จะแสดงออกมาใน Console

โปรดติดตามตอนต่อไป…