1

I use middleware for my back-end which processes each exception and produces JSON response which looks as follows:

{"error":"System.Exception: 'You must be logged in to perform this action.'"}

In my Angular app I would like to show a notification carrying the exception text each time the exception occurs, but I'm not entirely sure about how to implement this.

I wonder if should use HttpInterceptor for that - I'm also not quire sure how to register them properly - they should be registered in root.module.ts to work app-wide, right?

Could someone recommend a workaround or provide code examples please?

3
  • do you want to use intercepter?? Commented Jul 24, 2018 at 11:55
  • @UnluckyAj yes, provided that it's the best approach Commented Jul 24, 2018 at 11:57
  • yes thats true because you can handle all notification type from there. Commented Jul 24, 2018 at 11:57

2 Answers 2

2

Definitely use an interceptor.

Start by creating a service and transform it to an interceptor :

import { Observable } from 'rxjs/Observable';

import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
      .catch(err => { /* Display your error here */})
      .handle(req);
  }
}

Next, you will need to provide it in your module :

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true },
  ]
Sign up to request clarification or add additional context in comments.

Comments

1

http-intercepter.ts

import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import {
    HttpEvent,
    HttpHeaders,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpRequest
} from '@angular/common/http';

import { AppService } from './../../core/services/citizen/app-services/app.service';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(
        private router: Router,
        private appService: AppService) {
    }

    /**
     * 
     * @param req - parameter to handle http request
     * @param next - parameter for http handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        /**
         * Handle newly created request with updated header (if given)
         */
        return next.handle(req).do((event: HttpEvent<any>) => {
            /**
             * Sucessfull Http Response Time.
             */
            if (event instanceof HttpResponse) {
                const elapsed = Date.now() - started;
            }

        }, (err: any) => {
            /**
             * redirect to the error_handler route according to error status or error_code
             * or show a modal
             */
            if (err instanceof HttpErrorResponse) {
                switch (err.status) {
                    case 0:
                        console.log("Error type 0")
                        break;
                    case 400:
                        console.log("Error type 400")
                        break;
                    case 401:
                        console.log("Error type 401")
                        break;
                    default:
                        break;
                }
            }
        });
    }
}

in module.ts:

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
  ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.