Is there a specific reason you would like to have two different approaches for the exact same error?
I have three suggestions.
My first suggestion would be to create a custom error for the one controller where you want a special handling of the error, let's say SpecialControllerArgumentNotValidException.class
. This way you would not break the pattern of having one Global Exception handler.
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class){...}
@ExceptionHandler(SpecialControllerArgumentNotValidException.class){...}
}
My second suggestion, as suggested above in the comments, is to try using @ExceptionHandler on the controller: (great examples can be found here: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc )
@RestController
@RequestMapping("/api/something")
public class SomethingController {
@PostMapping
public ResponseEntity<String> createSomething(@Valid @RequestBody SomethingDto) {
return ResponseEntity.ok("Something created");
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
String mis = ex.getBindingResult()
.getFieldErrors()
.stream()
.findFirst()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.orElse("XX");
Map<String, Object> resposta = new HashMap<>();
resposta.put("X", -2);
resposta.put("X", mis );
return new ResponseEntity<>(resposta, HttpStatus.BAD_REQUEST);
}
...
}
My third suggestion would be to use this approach :
If we want to selectively apply or limit the scope of the controller advice to a particular controller, or a package, we can use the properties provided by the annotation:
@ControllerAdvice(annotations = Advised.class)
: only controllers marked with the@Advised
annotation will be handled by the controller advice.
taken from here: https://reflectoring.io/spring-boot-exception-handling/?utm_source=chatgpt.com