Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

How can i get error message returned by web api in Angular.

This is what I have got in fiddler

{"Message":"The request is invalid.","ModelState":{"":["Name test1 is already taken."]}}

 ()''

what do i change in error function to show just 'Name test1 is already taken'? This is Angular http post.

        $http({
            method: 'POST',
            url: 'api/Account/Register',
            data: { 'UserName': user.username, 'Password': user.password, 'ConfirmPassword': user.confirmpassword, 'Email': user.email },
        })
        .success(function () {
            toastr.success('successfully registered. ');                        
        })
        .error(function (error) {           
            toastr.error('error:' + error);                
        });
share|improve this question
up vote 1 down vote accepted

The response you get from the server is quite surprising. It does not look like a valid json string. the first item in model state has no id.

{"Message":"The request is invalid.","ModelState":{"":["Name test1 is already taken."]}}

should be something like:

{"Message":"The request is invalid.","ModelState":{"message":["Name test1 is already taken."]}}

and then you could access to your message with

error.ModelState.message[0]

It should work, although the error response look too complicated. Why is the error message in an array? Isn't it possible to simplify the response like this:

{"Message":"The request is invalid.","ModelState":{"message":"Name test1 is already taken."}} 

or

{"Message":"The request is invalid.","ModelState": "Name test1 is already taken."} 

Or if you need several error messages to be returned at once:

{"Message":"The request is invalid.","ModelState": ["Name test1 is already taken."]}  

In this last example you could access the messages by iterating on error.ModelStage

share|improve this answer
    
thanks Pascel .. your answer is great. – lawphotog Feb 26 '14 at 9:13
ModelState[""][0] 

that will give you just the message

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.