Laurence
Laurence

Reputation: 7823

How to get error message from web api in angular?

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);                
        });

Upvotes: 1

Views: 3347

Answers (3)

Sam MirzaGharcheh
Sam MirzaGharcheh

Reputation: 117

This code has worked for me:

$scope.message = response.statusText + "\r\n";
if (response.data.modelState) {
    for (var key in response.data.modelState) {
        $scope.message += response.data.modelState[key] + "\r\n";
    }
}
if (response.data.exceptionMessage)
    $scope.message += response.data.exceptionMessage;

Upvotes: 0

Jason
Jason

Reputation: 21

ModelState[""][0] 

that will give you just the message

Upvotes: 1

Pascal Le Merrer
Pascal Le Merrer

Reputation: 5981

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

Upvotes: 1

Related Questions