Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying Custom Server Side Error Message in Angular and .Net Core API

I have some rest API written in C# and the API is called from Angular (I am using version Angular 8). The call is fine and it is working fine. However, in case of any exception, I cannot display the customized error message in angular. For example, suppose I have a server side validation in C# which validates if the value of a field matches with the string "abc". If it does not match, it will throw an error and in UI (developed in Angular), I want to display the message

"Invalid String Specified".

My server side code is as below -

if (headerValues.Equals("abc")) {
    throw new InvalidStringException("Invalid String specified", 999);
}

The Invalid InvalidStringException class is as below -

public class InvalidStringException : System.Exception
{
    int status { get; set; }
    public InvalidStringException() { }
    public InvalidStringException(string message, int status) : base(message) {
        this.status = status;
     }
}

When that exception is thrown and caught in server side, it is available as 500 exception but could not print the custom message.

I am trying following code in Angular -

} catch (error) {
  console.log("Error Status: ", error.status);
  console.log("Error Status: ", error.message);
}

Please suggest how to handle that scenario.

like image 248
java developer Avatar asked Dec 22 '22 18:12

java developer


1 Answers

The error object that your Angular app receives should be an instance of HttpErrorResponse

You could do something like this to handle http errors:

if (error instanceof HttpErrorResponse) {
  if (!error.status) {
    console.log(error.message || error.toString());
  } else {
    console.log(`error status : ${error.status} ${error.statusText}`);
    switch (error.status) {
      case 401:
        this.router.navigateByUrl("/login");
        break;
      case 500:
        this.router.navigateByUrl("/login");
        console.log(`redirect to login`);
        break;
    }
  }
} else {
  console.error("Other Errors");
}

like image 171
adrisons Avatar answered Dec 25 '22 11:12

adrisons