I am trying to return a custom error message to the user to let them know what went wrong if an error occurs, but I have tried everything to display the message and nothing
Replace .error() by .catch().
$http.post('/url',json)
.success(function(data, status, headers, config){
// some code here
})
.catch(function(data, status, headers, config){ // <--- catch instead error
data.statusText; //contains the error message
});
For anyone else who may have had this issue, the message was in data.Message
. I found it by debugging the JS.
StatusText is only available by using the .then from $http, NOT from .Post helper methods and NOT from .success .error.
function handleSuccess(data, status, headers, config, statusText){
//some function of your own invention
}
function handleError(data, status, headers, config, statusText){
//some function of your own invention
}
//borrowed from angularJs Http module
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
//borrowed from angularJs Http module
function isSuccess(status) {
var istatus = Math.max(status, 0);
return 200 <= istatus && istatus < 300;
}
$scope.postMyData = function ($http)
{
var req = {
method: 'POST',
url: 'destinationURL.html',
headers: {
'Content-Type': 'application/json'
},
data: $scope,
};
// example response from :
//http://plnkr.co/edit/atRTBQC62YdZzKH8mWqu?p=preview
//{
// "data":"Hello, $http!",
// "status":200,
// "config":{
// "method":"GET",
// "transformRequest":[null],
// "transformResponse":[null],
// "url":"http-hello.html",
// "cache":{},
// "headers":{"Accept":"application/json, text/plain, */*"}
// },
// "statusText":"OK"}
$http(req).
then(function (response) {
var data = response.data;
var status = response.status;
var headers = headersGetter(headers)
var config = response.config;
var statusText = response.statusText;
scope.messageToUsers = (isSuccess(response.status))
? handleSuccess(data, status, headers, config, statusText)
: handleError(data, status, headers, config, statusText);
})
}