I got a behaviour I don't understand on an application using Spring and angular. An exception is Thrown in the http request. I did the test below.
@RequestMapping(value = "/contract/upload/excel", method = RequestMethod.POST)
public String uploadContractExcel(HttpServletRequest request, ModelMap model) {
if(true) {
throw new RuntimeException("my code is broken");
}
...
In JavaScript in the $http function instead of going into the error block, it returns to the success block with Status code 200 - OK. So I cannot handle any exception.
$http({
method : 'POST',
url : resolveAjax,
data : formData
}).then(
function successCallback(response) {
var data = response.data;
if (data.upload_error === "true") {
$scope.busy = false;
$scope.upload_error_message = data.upload_error_message;
} else {
$scope.contractSummary = angular
.fromJson(data.reference_excel_resolved);
$scope.busy = false;
$scope.tabindex = $scope.tabindex * 1 + 1;
}
},
function errorCallback(response) {
$scope.upload_error_message = 'Oups something went wrong';
});
Has anybody got an idea about what happens ? Thanks
If you want your client to receive a bad HTTP status like 400 etc, you should return such status in your controller. Throwing an exception will not suffice.
You have a couple of options; don't throw the exception or create a @ControllerAdvice which handles exceptions for you.
PSEUDOCODE:
@RequestMapping(value = "/url", method = POST)
public ResponseEntity postYourObject(@RequestBody YourObject object) {
if (true) {
return new ResponseEntity<>("Something happened", HttpStatus.BAD_REQUEST);
}
}
Or keep throwing your exception and create a controller advice like this.
@ControllerAdvice
public class GlobalControllerBehavior {
@ExceptionHandler
public ResponseEntity handleException(YourException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
Bottom line, if you don't return a HTTP status code like 4xx or 5xx your JavaScript error block will not be excecuted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With