3

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

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ok many thanks for your explaination. I thought an exception would return by default a code different from 200 in the controller. I will test that.
0

I know its been long, but even if there is an exception on server side, it is ultimately a form of response that the client receives, and hence the HTTP status 200.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.