001package co.codewizards.cloudstore.rest.server;
002
003import javax.ws.rs.WebApplicationException;
004import javax.ws.rs.core.Context;
005import javax.ws.rs.core.MediaType;
006import javax.ws.rs.core.Response;
007import javax.ws.rs.ext.ExceptionMapper;
008import javax.ws.rs.ext.Provider;
009
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013import co.codewizards.cloudstore.core.concurrent.DeferredCompletionException;
014import co.codewizards.cloudstore.core.dto.Error;
015
016/**
017 * @author Marco หงุ่ยตระกูล-Schulze - marco at codewizards dot co
018 * @author Chairat Kongarayawetchakun - ckongarayawetchakun at nightlabs dot de
019 */
020@Provider
021public class DefaultExceptionMapper implements ExceptionMapper<Throwable>
022{
023        private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionMapper.class);
024
025        public DefaultExceptionMapper(@Context final CloudStoreRest cloudStoreRest) {
026                logger.debug("<init>: Instance created. cloudStoreRest={}", cloudStoreRest);
027
028                if (cloudStoreRest == null)
029                        throw new IllegalArgumentException("cloudStoreRest == null");
030
031        }
032
033        @Override
034        public Response toResponse(final Throwable throwable)
035        {
036                // We need to log the exception here, because it otherwise doesn't occur in any log
037                // in a vanilla tomcat 7.0.25. Marco :-)
038                if (throwable instanceof DeferredCompletionException) // normal part of protocol => only debug
039                        logger.debug(String.valueOf(throwable), throwable);
040                else
041                        logger.error(String.valueOf(throwable),throwable);
042
043                if (throwable instanceof WebApplicationException) {
044                        return ((WebApplicationException)throwable).getResponse();
045                }
046
047                final Error error = new Error(throwable);
048                return Response
049                                .status(Response.Status.INTERNAL_SERVER_ERROR)
050                                .type(MediaType.APPLICATION_XML)
051                                .entity(error)
052                                .build();
053        }
054}