简体   繁体   中英

@ControllerAdvice method is not getting executed and it executes Base Response Class

I wrote my Spring Boot ProductController Class with productDetail method & handleMethodArgumentNotValid method . handleMethodArgumentNotValid method is annotated with @ExceptionHandler(MethodArgumentNotValid.class). It worked perfectly fine. After that I removed handleMethodArgumentNotValid method from Controller class, as I would like to use @ControllerAdvice. But it is executing BaseException class of the project. It is not executing @ControllerAdvice method.

Here is my Controller class.

 @PostMapping("/productDetail")
    public void productDetail(@Valid @RequestBody ProductDetail productDetail) {
        System.out.println("I am in Controller ProductDetail ....");
        try {
            iOrderService.updateProductDetail(productDetail);
        } catch (Exception e) {
            //Executes Base Exception class information here
            ...
        }
    }

Here is my ControllerAdvice .
  
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

  @Override
  @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
  protected ResponseEntity<Object> handleMethodArgumentNotValid(
      MethodArgumentNotValidException ex,
      HttpHeaders headers,
      HttpStatus status,
      WebRequest request
  ) {
      same code that I had in handleMethodArgumentNotValid method of ProductController class here 

ErrorResponse errorResponse = new ErrorResponse(
        HttpStatus.UNPROCESSABLE_ENTITY.value(), 
        "Validation error. Check 'errors' field for details."
    );
    
    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
      errorResponse.addValidationError(fieldError.getField(), 
          fieldError.getDefaultMessage());
    }
    return ResponseEntity.unprocessableEntity().body(errorResponse);
  }

How can I handle MethodArgumentNotValidException so that it won't execute BaseException class?

Your global exception handler can only handle uncaught exceptions. So if you want it to handle anything thrown by iOrderService.updateProductDetail(productDetail); , you'll need to remove the try/catch.

I suspect that your test input to productDetail() is not actually causing a MethodArgumentNotValidException . Either that or your global exception handler is not included in your component scan. I'd recommend adding a "catchAll" method to your global exception handler for testing purposes. Just to see if it's catching any exceptions at all.

  @ExceptionHandler(Exception.class)
  protected ResponseEntity<ExceptionEnvelope> catchAll(Exception exception, WebRequest request) {
    return buildResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception, request);
  }

Set a breakpoint in there and just see if you're able to hit it. I've had issues like this before and it ended up being that my assumptions were incorrect about which exceptions spring throws for different circumstances. Catching all exceptions like this will allow you to validate that the GlobalExceptionHandler is wired up properly, and will also tell you which exception is actually getting thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM