2

So I would like to get in console an json array with message, what would be equal with "Your direct manager have no account for your area."

But all I am getting is "Http failure response for https://localhost:44385/api/Option/Post: 500 Internal Server Error"

Note: When looking at dev tools -> network -> post -> response, then it shows html and css with right error message included, but no idea how to get it out from there.

Controller

[HttpPost("[action]")]
public void Post(Option option)
{
    throw new NoBudgetAccountException();
}

Exception

[Serializable]
public class NoBudgetAccountException : Exception
{
    public NoBudgetAccountException() : base("Your direct manager have no account for your area.")
    {
    }
}

Angular apiService

addOrUpdateOption(option: ITrainingOption): Observable<Response> {
    return this.post<Response>("api/Option/Post", option);
  }

Angular component

submitOption(option: ITrainingOption) {
        this.apiService.addOrUpdateOption(option).subscribe(() => {
            this.isAddOptionShown = false;
            this.getHeadlines(this.selectedYear);
          },
          err => { console.log(err); });
      }
5
  • Are you using Http or HttpClient? Commented Oct 28, 2018 at 10:45
  • I am using HttpClient Commented Oct 28, 2018 at 11:12
  • Does your console.log get printed? You should be able to use console.log(err.error) to get the body Commented Oct 28, 2018 at 11:22
  • Yes, it prints the whole body, but I would like to get only this "Your direct manager have no account for your area." so I can put it in error field and show it to user. Commented Oct 28, 2018 at 11:31
  • Okay, can you please edit your question to show what the full response looks like? Commented Oct 28, 2018 at 11:33

1 Answer 1

3

usually with .net stuff when you do something like

throw new Exception("This is a custom exception");

It doesn't actually give you this message, instead it throws you an error html page enter image description here

If you want to return a message and parse it in angular use an IActionResult instead and return BadRequest("message")

    [HttpPost("[action]")]
    public IActionResult test(Option option)
    {
        return BadRequest("This is an error message");
    }

After doing this your error message should show in err.error

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Will accept this, but used StatusCode() instead of BadRequest() and will use it in try and catch to get message from exception.
Yup, you can send anything really. You can even extend these. Ok(), BadRequest(), StatusCode() etc..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.