ControllerAdvice for Catching Exception in Rest Controller
For catching exception in rest controller, one can create a class with @ControllerAdvice
on the top of it. Here is an example for it. Assume we have an Error class that create POJO instance.
The controller advice will catch the exception according to the exception class that put inside @ExceptionHandler() above each method. For instance, @ExceptionHandler(NoAccessRightException.class) will catch all NoAccessRightException in case we have not catch it in the controller.
Note that the method return type
and the method in the controller that caused the exception should match
.
@ControllerAdvice public class ExceptionController { private static Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class); @ExceptionHandler(Exception.class) public ResponseEntity<Object> handle(Exception ex, HttpServletRequest request, HttpServletResponse response) { Error error = new Error(new Date(), "Server Error Message", "Server Error Details"); return new ResponseEntity<>(errorInfo, 500); } @ResponseBody @ExceptionHandler(NoAccessRightException.class) public byte[] handleNoAccessRightError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception ex) { LOGGER.error("Request: " + httpServletRequest.getRequestURL() + " raised " + ex, ex); httpServletResponse.setStatus(500); return null; } }