Issue
I have used the validation in my project to handle the exceptions but now I know @ ControllerAdvice is also used for exception handling can anyone tell me why I use it and what the difference is and how to use it, as I am not able to understand from the resources.
Using validation :
@RestController
@RequestMapping("/api")
@Validated
public class UserController {
@Autowired
UserRepository userrepo;
@PostMapping(value="/users")
ResponseEntity<?> create( @Valid @RequestBody User user) {
User addeduser = userrepo.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(addeduser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
Using ControllerAdvice:
@ControllerAdvice
public class GlobalResponseException {
@ExceptionHandler(MyException.class)
public void handleMyException() {}
}
Want I really want to know is how it's working.
Solution
@ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar. you can also refer this: https://medium.com/@jovannypcg/understanding-springs-controlleradvice-cd96a364033f
Answered By - Janil101
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)