I am trying to validate the postal code in my but the approach i am thinking of is not working out and I can't understand why.
I created a Validator, that hast to throw a ValidationException
if it's not valid.
@Service
public class ZipCodeValidator{
public void validate(String zipCode){
validateNotEmpty(zipCode);
validateHasNoSpaces(zipCode);
}
private void validateNotEmpty(String zipCode){
if (zipCode.length() != 0){
throw new ValidationException("Postal Code can't be empty");
}
}
private void validateHasNoSpaces(String zipCode) {
if (zipCode.contains(" ")){
throw new ValidationException("Postal Code can't contain spaces");
}
}
}
In my service, where i receive the postal code I want to throw my custom exception (to which i pass the error message) like this:
try{
validator.validate(zipCode);
}catch (ValidationException ex){
throw new ZipCodeValidationException(ex.getMessage());
}
However it doesn't seem to work, that exception is not caught so the program runs further.
What am I doing wrong?
Is the whole approach wrong? What would you recommend?
Here's my custom Exception
public class ZipCodeValidationException extends Exception{
public ZipCodeValidationException(String message) {
super(message);
}
}
I recommend the following:
ExceptionHandler
class, for more details see: https://www.baeldung.com/exception-handling-for-rest-with-springValidationException
fromRuntimeException
, that approach will allow unloading the code from try-catch constructionsPlease share the code for more suggestions and help.