Handling Errors in Angular 4

If a client sends a POST request with a LicenseNumber that already exists in the database (and must be unique), the server will respond as follows:

{"errorCode":"Validation Error",

"errorMessage":"Invalid inputs.",

"errors":["Such license number already exists"]}

How can I display the "errors" message in my view?

I attempted to do so with the following method:

   update(doctor: Doctor): Promise<Doctor> {
    const url =`${this.doctorsUrl}/${doctor.id}`;
    return this.http.put(url, JSON.stringify(doctor), {headers: this.headers})
    .toPromise()
    .then(() => doctor)
    .catch(this.handleError);
  }

  private handleError(errors: any): Promise<any> {
    console.error('An error occurred', errors);
    return Promise.reject(errors.message || errors);
  }

However, when I send a test bad request in the console, I only get a regular 400 BAD_REQUEST ERR.

Any suggestions on how I can catch this specific error?

Thank you, Bartek

Answer №1

What type of response is being received from the server? It seems like the server is returning an HTTP400 (Bad Request) error, which is a common result for this type of issue.

To display the error to the user, you can either return the error message directly or utilize a Toast/Snackbar to present it on the screen.

You have the option to implement the following:

private handleErrors(errors: any): Promise<any> {
   console.error('An error occurred', errors);
   // Using Angular Material Snackbar
   this.snackBar.open('Error occurred ' + errors.message, null, {
        duration: 5000
   });
   // Alternatively, you can use a browser alert
   alert('Error occurred ' + errors.message);
   return Promise.reject(errors.message || errors);
}

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

What is the best way to incorporate Form Projection into Angular?

I have been attempting to incorporate form projection in Angular, inspired by Kara Erickson's presentation at Angular Connect in 2017, but I am encountering difficulties and errors along the way. view talk here The code provided in the slides is inco ...

Is it feasible to deduce the generic type of a function by considering all remaining arguments?

I'm working with code that looks like this: type Boxed<T> = { inner: T } const box = <T>(inner: T): Boxed<T> => ({ inner }); function test<T extends Boxed<any>>(...args: T[]): T extends Boxed<infer I> ? I : ne ...

I encountered an issue trying to locate the module '@angular/compiler-cli'

I've encountered an issue with my new project as it's not allowing me to run 'ng serve' due to the 'cannot find module @angular/compiler-cli' error. Despite trying to clear the cache and deleting the node_modules folder withi ...

Determine the outcome of the subscription using an if/else statement

I'm working on a function that needs to return a boolean value based on the result of an http post request. Here's what I have so far: checkPost(callRequest: boolean): boolean { console.log('START REQUEST'); if(call ...

Web application experiences freezing issues when utilizing specific components in certain situations

Currently, I am in the process of developing a web application using Angular. In this project, there is a parent component and multiple child components that receive data from an rxjs Subject. One of the child components is being used in another section o ...

Creating dynamic text bubble to accommodate wrapped text in React using Material-UI (MUI)

I am currently developing a chat application using ReactJS/MUI, and I have encountered an issue with the sizing of the text bubbles. The bubble itself is implemented as a Typography component: <Typography variant="body1" sx={bubbleStyle}> ...

Passing a value to a property with a dynamically passed name in TypeScript

I'm encountering an eslint/typescript error message: errorUnsafe member access .value on an any value @typescript-eslint/no-unsafe-member-access when attempting to assign a value to a dynamically named property: selectChange(name: string, value: stri ...

Dealing with Type Casting Problems Following the Migration to Angular 4

Following my upgrade to Angular 4, I encountered the error mentioned below [enter image description here][1] client?afea:119 [at-loader] ./src/test/javascript/spec/app/account/settings/settings.component.spec.ts:49:13 TS2322: Type 'Principal&apo ...

Having an issue with Vue-loader where it's throwing an error for an unexpected

After executing the webpack command, I encounter an unusual error within the vue-loader library. ERROR in ...\node_modules\vue-loader\lib\parser.js:25 output.styles.forEach(style => { ^^ Unexp ...

Error: Attempting to initiate a backward navigation action while already in the process. Utilizing Natiescript

I encountered an issue with the routing code in my Nativescript app. Here is the code snippet: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ {path: 'fp&apos ...

What is the proper way to conduct unit testing on a function that is invoked in a service's constructor

Is there a way to verify, within the service's spec file, that a function is invoked in the constructor? Consider the following example: @Injectable({ providedIn: 'root' }) export class myService { constructor() { this.myF ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

Eliminating Body Tag Margin in Angular 4: A Step-by-Step Guide

In the Angular 4 project, the app.component.html file does not include a body tag that can be styled to eliminate the padding associated with the body tag. https://i.sstatic.net/5QS9x.jpg An attempt was made in the app.component.css file to remove the ma ...

Upgrading from Angular 5.2 to 6.0: Facing an issue where angular.json does not replace angular-cli.json

After diligently following the official documentation to upgrade from Angular 5.2 to Angular 6.0 (with the end goal of migrating to Angular 13), I found myself at a standstill. Executing the command NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @an ...

"Error occurs as a result of an unspecified attribute in the map

Hello, I am currently traversing a tree structure recursively. To handle undefined nodes in the tree, I have implemented guards to prevent any failures. However, during the mapping of children nodes, I encountered the following error: Error Output Adri ...

Transform JSON object array into a different format

Can anyone help me with an issue I am facing with checkboxes and arrays in Angular 2? I have checkboxes that capture the value "role". Each role is stored in an array called "selectedRoles". However, when I try to console.log this.selectedRoles, I get str ...

"Implementing Hot Module Replacement in Electron: A Step-by-Step Guide

Is there a way to enable Hot Module Replacement (HMR) in a React Electron application? Do I need webpack for this integration, and how can it be seamlessly implemented alongside Electron? ...

What makes it impossible to use var instead of let in ngFor?

My understanding is that in JavaScript, we typically use var and let for variable declarations. The main difference between the two is that var is scoped to the current function, while let is scoped to the current block. Therefore, theoretically I should b ...

Using RxJS iif with various conditions in combination with Angular 9

I am currently working on creating a service using Angular that will retrieve a specific data set. The format of the object returned by the API looks like this: { status: string, totalResults: number, results: [array of objects] } My goal is to ret ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...