0

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.

SpringDev
  • 3
  • 2
  • 1
    No. The exception handler is already part of the exception path inthe dispatcher servlet, so you are already passed that. Also what makes you think that removing the special characters would fix it? What if a string was given for a number, or the value is plain invalid, then what? How would you fix that? – M. Deinum Mar 07 '22 at 19:32
  • @M.Deinum The given example is arbitrary and not meant to provide a bullet-proof use case. I didn't want to spend time accounting for edge cases in a non-existent application. – SpringDev Mar 07 '22 at 20:31

1 Answers1

1

It is not acceptable. ExceptionHandler is a common place where we can manage and handle exceptions and send the respective error code for the API response.
See documentation.
It is designed for:

  • Handle exceptions without the @ResponseStatus annotation (typically predefined exceptions that you didn’t write)
  • Redirect the user to a dedicated error view
  • Build a totally custom error response


In your case special characters should be handled at json serialisation\deserialisation stage. Escape JSON string in Java

Eugene
  • 5,269
  • 2
  • 14
  • 22