Home > database >  Can the Spring ExceptionHandler be used to re-run endpoints?
Can the Spring ExceptionHandler be used to re-run endpoints?

Time:03-08

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.

CodePudding user response:

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

  • Related