Issue
I do have a Spring boot controller class and a corresponding ControllerAdvice class which has ExceptionHandlers to handle different exception. My controller method calls a simple validation helper class to validate input fields which throws an exception if validation fails. Now if I don't put a try catch block in my controller it keeps complaining me that you have a method which has untangled exception even through the logic for handling validation exception is defined in controlleradvice class. Please suggest how do I solve it.
Solution
From the method of ValidationHelper class if you throw any Checked Exception then you need to use a try-catch block to call that method.
If you don't want then it's better to use any Custom Exception class which will extend the RuntimeException class and you throw that exception. Then you don't need to explicitly mention the throws as well as you don't need to have a try-catch block at the controller.
@RestController
@RequiredArgsConstructor
public class SampleController {
private final ValidationHelper validationHelper;
@ResponseStatus(HttpStatus.OK)
@GetMapping("/sample")
public String getRequest(@RequestParam String name) {
validationHelper.validate(name);
return "";
}
}
@Service
public class ValidationHelper {
public Boolean validate(String name) {
throw new CustomException("Validation Failed");
}
}
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
Answered By - Santanu
Answer Checked By - Willingham (JavaFixing Volunteer)