Chenna
Chenna

Reputation: 2623

Angular Client Side Errors Log to Server

I want to log to client side angular errors to Server, so I followed this and this stackoverflow answers and implemented a service which makes a http call server. For now the logError method is getting hit but http call is not made to server.

export class AngularLoggerService {
constructor(private http: HttpClient) {}

logError(error: Error) {
   console.log(error.stack); // line is printed to console
   this.http.post('/angular/log', {
     message: error.stack
   });
 }
}

Stackblitz Link

Image

Upvotes: 5

Views: 13076

Answers (2)

TheParam
TheParam

Reputation: 10571

You need to pass the baseUrl (server URL) in your post method and also subscribe to that Observable so that you will get the response back about error log successfully or not. Here is a solution.

service.ts

import { Injectable, isDevMode } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AngularLoggerService {

  baseUrl = "https://yourserver.com"
  constructor(private http: HttpClient) {}

  logError(error: Error) {
    console.log(error.stack);
    this.http.post(this.baseUrl +'/angular/log', {
      message: error.stack
    }).subscribe( (response) => {
      console.log(response);
    });
  }
}

Here is Forked Stackblitz solution

Hope this will help!

Upvotes: 0

Nithya Rajan
Nithya Rajan

Reputation: 4884

this.http.post returns an observable unless you use .subscribe method in the observable, the server call wont be made change your code as follows

export class AngularLoggerService {
constructor(private http: HttpClient) {}

    logError(error: Error) {
       console.log(error.stack); // line is printed to console
       this.http.post('/angular/log', {
         message: error.stack
       }).subscribe((res) => console.log(res));
     }
    }

Upvotes: 7

Related Questions