Home > Software design >  How to display exception from backend in Angular?
How to display exception from backend in Angular?

Time:01-27

I'm preparing WebAPI in .Net6 with Angular. When I prepared the registration page, I set up the email to be unique (it's a username credential). Now, I'd like to show that email is not unique when a user tries to register with an already taken email. The email column in DB is set to be unique, but I don't know how to handle the error from the backend in the frontend. Somehow user has to know what he did wrong during registration. I am throwing an exception when I can find provided email in the database. Maybe I should do this in another way? Give some hint :) Registration method

public void RegisterUser(UserRegister dto)
        {
            var newUser = new User()
            {
                Email = dto.Email,
                RoleId = dto.RoleId,
                FirstName = dto.FirstName,
                LastName = dto.LastName,
                DateOfBirth = dto.DateOfBirth,
                Nationality = dto.Nationality,
            
            };
            
            if(_dataContext.Users.Where(m => m.Email == newUser.Email).Any())
            { 
                throw new BadRequestException("Email exists"); 
            }

            var hashedPassword = _passwordHasher.HashPassword(newUser, dto.Password);

            newUser.PasswordHash = hashedPassword;
            _dataContext.Users.Add(newUser);
            _dataContext.SaveChanges();
        }

Component responsible for registration

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Form, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { User } from '../models/user';
import { UserService } from '../services/user.service';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor(private http: HttpClient, 
    private userService: UserService,
    private router: Router) { }

  userRegisteredSuccessfully : boolean = false;

  public countries:any = countries
  
    ngOnInit(): void {
      this.userRegisteredSuccessfully = false

  }

  

  onSubmit(f: NgForm){
    this.userService.registerUser(f.value).subscribe(
      res =>{
        var showRegisteredSuccess = document.getElementById('register-success-alert');
        if (showRegisteredSuccess) {
          showRegisteredSuccess.style.display = "block";
        }
        setTimeout(function () {
          if (showRegisteredSuccess) {
            showRegisteredSuccess.style.display = "none";
          }
        }, 4000);
      },
      err => {
        //What do do here ? 
      }  
    );
  }

}

CodePudding user response:

This is a very customizable feature for every app. It depends on:

  1. what error the BE will send.
  2. what errors do you want to expose to the user. (Not all error should be explicit for FE)
  3. Do you want to translate error messages.

I would recommend discussing this whole as a team. If it is a pet project, then you can try angular snack bars or other types of toast components that are available out there.

onSubmit(f: NgForm){
    this.userService.registerUser(f.value).subscribe(
      res =>{
        var showRegisteredSuccess = document.getElementById('register-success-alert');
        if (showRegisteredSuccess) {
          showRegisteredSuccess.style.display = "block";
        }
        setTimeout(function () {
          if (showRegisteredSuccess) {
            showRegisteredSuccess.style.display = "none";
          }
        }, 4000);
      },
      err => {
        this._snackBar.open(err.message, 'Ok');
      }  
    );
  }

example here

CodePudding user response:

You can write your custom exception middleware in dotnet api like explained in this link Middleware not returning error details to API request. After implementation of this middleware you can capture all errors from client side and then you just show it to user for information purposes.

  •  Tags:  
  • Related