0

I have created a custom exception handler in Spring Boot:

@RestControllerAdvice
public class DataApiExceptionHandler extends ResponseEntityExceptionHandler {
 @ExceptionHandler(NoSuchElementException.class)
        public final void **handleNoSuchElementException**(NoSuchElementException ex) {
            System.err.println("This is throwing :"+ex.getMessage());
        }
...
@ExceptionHandler({ Exception.class })
    public ResponseEntity<Object> **handleAll**(final Exception ex) {
...

and it's throwing exception like

throw new NoSuchElementException("SomelogicalDescription");

but each time I throw this NoSuchElementException, handleAll is executed instead of handleNoSuchElementException.

I might be missing something very trivial. To change NoSuchElementException with NotFoundException does not make any difference.

halfer
  • 19,824
  • 17
  • 99
  • 186
Rishi
  • 1,646
  • 2
  • 15
  • 34
  • 1
    Have you had a look at https://stackoverflow.com/questions/19498378/setting-precedence-of-multiple-controlleradvice-exceptionhandlers – sfiss Jan 28 '20 at 08:56
  • No I haven't, I am doing that now. Thank you – Rishi Jan 28 '20 at 08:57
  • Anyone looking for specific answer please go to https://stackoverflow.com/questions/38462588/order-of-exceptionhandler – Rishi Jan 28 '20 at 09:00
  • 1
    just remove (just for verify) handleAll**() all then check if call comes to handleNoSuchElementException**() – Ganesh Gudghe Jan 28 '20 at 09:16
  • 1
    This has been marked by the OP as being a duplicate of: [Order of @ExceptionHandler](https://stackoverflow.com/questions/38462588/order-of-exceptionhandler) – halfer Feb 13 '23 at 20:25

1 Answers1

0

It looks like you doesn't understand a @RestControllerAdvice activity:

NOTE: @RestControllerAdvice is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace. RestControllerAdvice

Use @ControllerAdvice instead: ControllerAdvice

You have a void handler - why do you expect a response then?

What do you return there? It should be like this:

@ControllerAdvice
public class InvalidValuesExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler({ InvalidValuesException.class })
  protected ResponseEntity<Object> handleInvalidRequest(RuntimeException exc, WebRequest request) {
    InvalidValuesException ive = (InvalidValuesException) exc;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

    BasicResultMessage msg = new BasicResultMessage(ive.getDataId(),
                                                    ive.getMessage());
    SendDataResult result = new SendDataResult(false, msg);

    return handleExceptionInternal(exc, result, headers, HttpStatus.BAD_REQUEST, request);
  }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Yuriy Tsarkov
  • 2,461
  • 2
  • 14
  • 28