Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests.

I want to implement error handling by using the HandleError mechanism described on Angular's Communication Page to properly display any errors encountered. However, I am facing an issue with the error handler in my data service layer throwing the error message:

Argument of type 'Observable<never>' is not assignable to parameter of type '(err: any, caught: Observable<Record>) => ObservableInput<any>'

Upon inspecting the JSON object and API URL, everything seems to be correct. I can successfully reach the controller by manually testing the JSON object and URL using Postman.

If anyone has insights or suggestions for effective error handling and logging, it would be greatly appreciated.

Below is the component logic:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord);
}

Data service logic:

put<Record>(record_id: number, record: Record): Observable<Record> {
    var url = this.baseUrl + `api/record/${record_id}`;
    let output = this.http.put<Record>(url, record, {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    })
    .pipe(
        catchError(this.handleError('put<Record>', record))
    );

    return output;
 }

Error Handling Function:

private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
        consol e.error('An error occurred:', error.error.message);
    } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong.
        console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // Return an observable with a user-facing error message.
    return throwError(
        'Something bad happened; please try again later.');
}

Controller logic:

[HttpPut("{id}")]
public async Task<ActionResult<Domain.Record>> Put(int id, [FromBody] Domain.Record record)
{
    //Confirm the request record and ID record being update match
    if (id != record.record_id)
        return BadRequest();

    //Modify the state
    _context.Entry(record).State = EntityState.Modified;
    //Update the records in DB.records, throw appropriate error if there is one.
    try
    {
        await _context.SaveChangesAsync();
    }
    catch(DbUpdateConcurrencyException)
    {
        if (!RecordExists(record.record_id))
            return NotFound();
        else
            throw;
    }

    //return 200 OK
    return NoContent();
}

Answer №1

It seems like a subscription was missing, as mentioned in the comments of the main question.

In RXJS, an Observable needs to be subscribed to in order for it to execute. So, instead of just:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord);
}

You should use:

updateRecord(record_id: number, newRecord: any): void
{
   this.recordService.put<Record>(record_id, newRecord).subscribe((result) => {
    // process the results here
   };
}

If you don't subscribe, you won't receive any results from the HTTP call made by recordService.put().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Setting Up Infinite Scroll with Next JS SSG

I recently built a markdown blog using the Next Js documentation and incorporated Typescript. When trying to retrieve a list of blog posts, I utilized getStaticProps as recommended in the documentation. However, my attempts with certain npm packages were u ...

TypeORM - Establishing dual Foreign Keys within a single table that point to the identical Primary Key

Currently, I am working with TypeORM 0.3.10 on a project that uses Postgres. One issue I encountered is while trying to generate and execute a Migration using ts-node-commonjs. The problem arises when two Foreign Keys within the same table are referencing ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

Is there a way to extract the "validade" value from the array and retrieve it exclusively?

The following array contains data: {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02- 01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade&quo ...

Merge two arrays by matching their corresponding identifiers

I have 2 separate arrays that I need to merge. The first array looks like this: const Dogs[] = [ { id: '1', name: 'Buddy' }, { id: '2', name: 'Max' }, ] The second one: const dogAges[] = [ { id: '4&ap ...

Setting up CI/CD for a project involving an API, Angular application, and database on Azure App Services

In my VSTS local GIT REPO, I have a solution file with three main projects: an API, an Angular App, and a SQL Server DB Project. There are also some test projects included in the solution. I am currently facing challenges in setting up CI/CD for this setu ...

Angular Proxy is not passing the WebSocket Upgrade Header

When using the Angular CLI proxy by running ng serve --proxy-config proxy.conf.json the configuration looks like this: { "/api/*": { "ws": true, "secure": false, "target": "http://localhost:80", "logLevel": "debug" ...

Out of the blue, Angular has inexplicably ceased to function in development, production, and local environments, despite successfully

TypeError: n is not iterable TypeError: n is not iterable I am currently working on an Angular and Node.js project hosted on Heroku. Everything was running smoothly until recently when I encountered an error after successfully building Angular. Upon loadi ...

Avoid accessing members in Vue 3 using TypeScript that may be unsafe

Recently, we initiated the process of upgrading from Quasar v1 to Quasar v2 (moving from Vue 2 to Vue 3). In the past, this code functioned without any issues: // src/pages/myComponent.vue <script lang="ts"> import { defineComponent } from ...

Establish a public-facing link for a React component

After developing a React component that functions as a chatbot window, I am now looking for a way to make the opening button accessible across various websites and applications. My initial thought was to associate a URL with the button so that it can be ea ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

What are the best ways to troubleshoot my Angular 2 project?

I've been searching for my TypeScript files in the console, but they're not showing up. I've tried everything to debug my Angular 2 project, but no luck. I can't move forward without debugging, can anyone lend a hand? ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

The variable's Ionic value is not being displayed in the HTML

I recently developed a new Ionic application and encountered an issue while attempting to display a variable value in the HTML. Without making any modifications, this is the current state of my page after creating the app. import { IonicModule } from &ap ...

How can I enable SCSS/SASS support on Parcel-Angular5?

I started a project using angular cli. My intention is to incorporate scss into the project. In the terminal of WebStorm, I entered : ng set defaults.styleExt scss I proceeded by renaming all the .css files to .scss and adjusted the imports accordingly ...

Implementing ngClass change on click within an Angular component using Jasmine: A comprehensive guide

It seems like the click event is not triggering and the ngClass is not changing to active on the button I am attempting to click. -- HTML: <div class='btn-group' role='group' aria-label=""> <button type='button&apos ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Exploring the terrain of observable data

Understanding how to filter an observable is really challenging for me right now. I have a gadget {name: string, description: string} I possess an observable collection of gadgets [{},{},{}] My goal is to iterate through my observable collection of ga ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

Node.js serves an Angular application without the need for additional JavaScript scripts

After developing an Angular application with a node.js server, I encountered an issue where the browser displayed the HTML code served by the server as text instead of rendering the web page correctly. This problem arose when I built the Angular project in ...