GeneralExceptionMapper implements ExceptionMapper<Exception> { @Override public Response toResponse(final Exception ex) { final String errorTrackingId = UUID.randomUUID().toString(); Tuple2<String, Status> error = new Tuple2<>(MapOfExceptionsToErrorCodes.INTERNAL_SERVER_ERROR, Status.INTERNAL_SERVER_ERROR); Optional<Tuple2<String, Status>> errorFromLookup = find(ex.getClass()); if (errorFromLookup.isPresent()) { error = errorFromLookup.get(); } else { if(ex instanceof javax.ws.rs.WebApplicationException){ javax.ws.rs.WebApplicationException rsEx = ((javax.ws.rs.WebApplicationException)ex); error = tuple(rsEx.getResponse().getStatusInfo().getReasonPhrase(),Status.fromStatusCode(rsEx.getResponse().getStatus())); } } logger.error(String.format("%s Error id: %s, %s", error._1(), errorTrackingId, ex.getMessage()), ex); Response.ResponseBuilder responseBuilder = Response.status(error._2()).type(MediaType.APPLICATION_JSON_TYPE); if (showDetails) { responseBuilder.entity(new ExceptionWrapper(error._1(), String.format("Error id: %s %s", errorTrackingId, ex.getMessage()))); } else { responseBuilder.entity(new ExceptionWrapper(MapOfExceptionsToErrorCodes.INTERNAL_SERVER_ERROR, errorTrackingId)); } return responseBuilder.build(); } GeneralExceptionMapper(Logger logger, boolean showDetails); @Autowired  GeneralExceptionMapper(@Value("${micro.general.exception.mapper.details:true}") Boolean showDetails); @Override Response toResponse(final Exception ex);  }
@Test public void whenEOFException_thenBadRequest() { assertThat(mapper.toResponse(new EOFException("test")).getStatus(), is(Status.BAD_REQUEST.getStatusCode())); }
@Test public void whenJsonProcessingException_thenBadRequest() { assertThat(mapper.toResponse(mock(JsonProcessingException.class)).getStatus(), is(Status.BAD_REQUEST.getStatusCode())); }
@Test public void whenNotFoundException_thenNotFound() { assertThat(mapper.toResponse(new NotFoundException()).getStatus(), is(Status.NOT_FOUND.getStatusCode())); }
@Test public void whenWebApplicationException_thenUnsupportedMediaType() { assertThat(mapper.toResponse(new NotSupportedException(Response.status(Status.UNSUPPORTED_MEDIA_TYPE).build())) .getStatus(), is(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode())); }
@Test public void whenRuntimeException_thenInternalServerError() { assertThat(mapper.toResponse(mock(RuntimeException.class)).getStatus(), is(Status.INTERNAL_SERVER_ERROR.getStatusCode())); }
@Test public void whenJacksonException_thenNotInternalServerError_NoErrorsLogged() { mapper= new GeneralExceptionMapper(mockLogger, true); assertThat(mapper.toResponse(new MyLocalException()).getStatus(), is((Status.INTERNAL_SERVER_ERROR.getStatusCode()))); verify(mockLogger, times(0)).error(any(String.class), any(Object[].class)); verify(mockLogger, times(0)).error(any(String.class), any(Throwable.class), any(Object[].class)); }