0

I am wondering what ~(event.status / 100) > 3 is doing in the below code taken from here?

  1. Is there a class of errors > 399?
  2. Why do we need ~ here?

   @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.info('req.headers =', req.headers, ';');
        return next.handle(req)
          .map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse && ~(event.status / 100) > 3) {
              console.info('HttpResponse::event =', event, ';');
            } else console.info('event =', event, ';');
            return event;
          })
          .catch((err: any, caught) => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 403) {
                console.info('err.error =', err.error, ';');
              }
              return Observable.throw(err);
            }
          });
      }
    }
sabithpocker
  • 15,274
  • 1
  • 42
  • 75

2 Answers2

3

~ is bitwise NOT operator. MDN

~(event.status / 100) > 3 is same as event.status <= -500.
Please see below snippet.

a = 200;
console.log( ~(a / 100) , ~(a / 100) >3 );
a = 300;
console.log( ~(a / 100), ~(a / 100) >3  );
a = 400;
console.log( ~(a / 100), ~(a / 100) >3  );

a = -200;
console.log( ~(a / 100), ~(a / 100) >3  );
a = -300;
console.log( ~(a / 100), ~(a / 100) >3 );
a = -400;
console.log( ~(a / 100), ~(a / 100) >3 );
a = -500;
console.log( ~(a / 100), ~(a / 100) >3 );
Goszczu
  • 168
  • 4
artgb
  • 3,177
  • 6
  • 19
  • 36
0

The code is determining if the HTTP response is either a information response or a successful Response. Since the information and successful responses range from the response codes 100 to 226. You can view a list of HTTP response codes at https://developer.mozilla.org/en-US/docs/Web/HTTP/Status . An HTTP response code is just telling you the current state of the connection to a URL. For example if the code is 226, it means that the web server is at the state "IM Used".

In the case of the code you showed it is logging the information and successful codes to the console while others are being let through and into the code that requires that information.

I hope that this will help you understand the functionality of the code.