I am facing an issue in my Angular factory where I need to display an alert when an error occurs.
Here is the code snippet for calling the factory:
gradeService.assignGrade(requestData).then(Controller.populateResponseObject, Controller.error);
The Controller
variable simply refers to the current controller with this line of code: var Controller = this
.
While attempting to trigger the error on the UI, a 500 Server Error is encountered as expected. However, instead of going to the error
function, it goes to the populateResponseObject
function. How can I make the service return the error properly?
Below is the relevant part of the service code:
app.factory('gradeService', function ($http) {
var baseUrl = "http://localhost:8080";
var add = function (request) {
var requestUrl = baseUrl + "/grade/new";
return $http.post(requestUrl, request)
.then(function (responseSuccess) {
return responseSuccess.data;
},
function (responseError) {
return responseError.data;
});
};
return {
assignGrade: add
};
});
And here is the snippet for handling errors (error
):
Controller.error = function (error) {
// ... some code
else if(error.status === 500) {
if(error.exception === "org.springframework.dao.DataIntegrityViolationException") alert("Error: this person has already been graded for this month. Grade was not saved.");
else if(error.exception === "java.sql.SQLException") alert("Error establishing connection with database. Please try again later.");
else alert("Error: " + error.message + ": Generic Server Error.");
}
};
I am using Spring for the backend implementation.
Any suggestions or assistance would be greatly appreciated.