'Can the Spring ExceptionHandler be used to re-run endpoints?

In my experience, limited though it may be, I have only ever seen the ExceptionHandler class used to immediately return exceptions. I know this is the purpose of an ExceptionHandler class but this brings me to my question: If a request fails validation, is it possible for the ExceptionHandler class to "fix" the request body and re-run the request?

As an example, given the following object:

public class Person {
    @Pattern(regexp = "[A-Za-z]")
    private String firstName;
}

Could the following Handler class:

@ExceptionHandler(ParameterNotValidException.class)
public Map<String, String> handleValidationExceptions(
  ParameterNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}

Be modified like this:

@ExceptionHandler(ParameterNotValidException.class)
public void handleValidationExceptions(String requestBody) {
    requestBody = removeSpecialCharacters(requestBody);

    try {
        personController.putPerson(requestBody);
    } catch (Exception e) {
        //fail gracefully
    }
}

My apologies in advance, this is my first question on StackOverflow.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source