مدیریت سراسری خطاها در یک برنامهی Angular
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۴/۱۲ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
fetchProducts(categoryId?: number) {
console.log(categoryId);
this.products = [];
if (categoryId === undefined || categoryId.toString() === "undefined") {
return;
}
> npm install ng2-toasty --save
npm ERR! Error: EPERM: operation not permitted, rename
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"../node_modules/ng2-toasty/bundles/style-bootstrap.css",
"styles.css"
], import { ToastyModule } from "ng2-toasty";
@NgModule({
imports: [
BrowserModule,
ToastyModule.forRoot(), <ng2-toasty [position]="'top-right'"></ng2-toasty>
import { ToastyService, ToastOptions } from "ng2-toasty";
export class ProductGroupComponent implements OnInit {
constructor(
private productItemsService: ProductItemsService,
private toastyService: ToastyService) { }
fetchProducts(categoryId?: number) {
console.log(categoryId);
this.products = [];
if (categoryId === undefined || categoryId.toString() === "undefined") {
this.toastyService.error(<ToastOptions>{
title: "Error!",
msg: "Please select a category.",
theme: "bootstrap",
showClose: true,
timeout: 5000
});
return;
}
this.productItemsService.getCategories().subscribe(
data => {
this.categories = data;
},
err => console.log("get error: ", err)
); > ng g cl app.error-handler
installing class create src\app\app.error-handler.ts
import { ErrorHandler } from "@angular/core";
export class AppErrorHandler implements ErrorHandler {
handleError(error: any): void {
console.log("Error:", error);
}
} import { NgModule, ErrorHandler } from "@angular/core";
import { AppErrorHandler } from "./app.error-handler";
@NgModule({
providers: [
{ provide: ErrorHandler, useClass: AppErrorHandler }
] [HttpGet("[action]/{categoryId:int}")]
public async Task<IActionResult> GetProducts(int categoryId)
{
throw new Exception(); this.productItemsService.getProducts(categoryId).subscribe(
data => {
this.products = data;
this.isLoadingProducts = false;
}// ,
// err => {
// console.log("get error: ", err);
// this.isLoadingProducts = false;
// }
);
import { ToastyService, ToastOptions } from "ng2-toasty";
import { ErrorHandler } from "@angular/core";
export class AppErrorHandler implements ErrorHandler {
constructor(private toastyService: ToastyService) {
}
handleError(error: any): void {
// console.log("Error:", error);
this.toastyService.error(<ToastOptions>{
title: "Error!",
msg: "Fatal error!",
theme: "bootstrap",
showClose: true,
timeout: 5000
});
}
} Uncaught Error: Can't resolve all parameters for AppErrorHandler: (?).
import { ErrorHandler, Inject } from "@angular/core";
export class AppErrorHandler implements ErrorHandler {
constructor(
@Inject(ToastyService) private toastyService: ToastyService
) {
} import { ToastyService, ToastOptions } from "ng2-toasty";
import { ErrorHandler, Inject, NgZone } from "@angular/core";
import { LocationStrategy, PathLocationStrategy } from "@angular/common";
export class AppErrorHandler implements ErrorHandler {
constructor(
@Inject(NgZone) private ngZone: NgZone,
@Inject(ToastyService) private toastyService: ToastyService,
@Inject(LocationStrategy) private locationProvider: LocationStrategy
) {
}
handleError(error: any): void {
// console.log("Error:", error);
const url = this.locationProvider instanceof PathLocationStrategy ? this.locationProvider.path() : "";
const message = error.message ? error.message : error.toString();
this.ngZone.run(() => {
this.toastyService.error(<ToastOptions>{
title: "Error!",
msg: `URL:${url} \n ERROR:${message}`,
theme: "bootstrap",
showClose: true,
timeout: 5000
});
});
// IMPORTANT: Rethrow the error otherwise it gets swallowed
// throw error;
}
}
>npm install >ng build --watch
>dotnet restore >dotnet watch run
npm install stacktrace-js --save npm install @types/stacktrace-js --save-dev
throw new Exception("the message of exception"); Error! URL:/lab ERROR:HTTP error occurred at 2018-05-07T07:34:32.291Z, message - Http failure response for http://localhost:50442/Master/GetAllMasters: 500 Internal Server Error, Status code - 500
if (error instanceof HttpErrorResponse) {
return `HTTP error [${error.error}] occurred at ${date}, message: ${error.message}, Status: ${(<HttpErrorResponse>error).status}: ${error.statusText}`;
} return StackTrace.fromError(error)
.then(stackFrames => stackFrames.splice(0, 20).map(stackFrame => stackFrame.toString()).join("\n")); zone.js:665 Unhandled Promise rejection: Cannot parse given Error object ; Zone: <root> ; Task: Promise.then ; Value: Error: Cannot parse given Error object
private handleError(error: Response): Observable<any> {
console.error("observable error: ", error);
return Observable.throw(error.statusText);
} private handleError(error: HttpErrorResponse): Observable<any> {
console.error("observable error: ", error);
return Observable.throw(error);
} private handleError(error: HttpErrorResponse): Observable<any> {
console.error("observable error: ", error);
return observableThrowError(error);
} خطا به صورت رشته ارسال نمیشه . نوع error رو ببینید
و نحوه فراخوانی به صورت زیر است
در کامپوننت
this.dynamicGridService.getMasters(queryModel).subscribe(res => {
console.log(res);
this.data = res;
}); سرویس:
return this.labApiService.get(`Master/GetMasterColumns`).pipe(
map(response => response)); سرویس اصلی
get(url: string): Observable<any> {
return this.http
.get<any>(url)
.pipe(
map(response => response || {}),
catchError(this.handleError));
} public handleError(error: HttpErrorResponse): Observable<any> {
console.error("observable error: ", error);
return observableThrowError(error);
}
اما باز هم متن اصلی خطارو نشون نمیده