Controller Advice

Introduction

  • Spring provides a useful way to handle the API exception using controller advises, which can handle all the exceptions thrown by controller classes.

  • Controller advice leverages the aspect-oriented programming principle, grouping cross-cutting concern of exception handling into one place

Implementation

public class ProductNotfoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct() { 
   throw new ProductNotfoundException();
}
// The @ControllerAdvice is an annotation, 
// to handle the exceptions globally.

// The @ExceptionHandler is an annotation used 
// to handle the specific exceptions and sending the custom responses to the client.

@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}

Last updated

Was this helpful?