RestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(RestException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); LOG.error("Encountered error: " + ex.getMessage(), ex); return new ResponseEntity<>(new RestError(status.value(), ex.getMessage(), ExceptionUtils.getRootCauseMessage(ex)), status); }    }
@Test public void handleControllerExceptionShouldProperlyReturnRestError() throws Exception { when(request.getAttribute("javax.servlet.error.status_code")).thenReturn(401); Throwable throwable = new RuntimeException("unauthorized"); ResponseEntity responseEntity = restExceptionHandler.handleControllerException(request, throwable); assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode()); RestError actualRestError = (RestError) responseEntity.getBody(); assertEquals("unauthorized", actualRestError.getMessage()); assertEquals("RuntimeException: unauthorized", actualRestError.getFullMessage()); assertEquals(401, actualRestError.getResponseCode()); }
@Test public void handleControllerExceptionShouldDefaultTo500() throws Exception { when(request.getAttribute("javax.servlet.error.status_code")).thenReturn(null); Throwable throwable = new RuntimeException("some error"); ResponseEntity responseEntity = restExceptionHandler.handleControllerException(request, throwable); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); }
@Test public void handleControllerExceptionShouldReturnRootCause() throws Exception { when(request.getAttribute("javax.servlet.error.status_code")).thenReturn(500); Throwable throwable = new RuntimeException("some error", new RuntimeException("some root cause")); ResponseEntity responseEntity = restExceptionHandler.handleControllerException(request, throwable); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); RestError actualRestError = (RestError) responseEntity.getBody(); assertEquals("some error", actualRestError.getMessage()); assertEquals("RuntimeException: some root cause", actualRestError.getFullMessage()); assertEquals(500, actualRestError.getResponseCode()); }