'How to display exception from backend in Angular?
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 ?
}
);
}
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Onurkan Bak?rc? |
