001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006package org.fcrepo.http.commons.exceptionhandlers;
007
008import org.fcrepo.kernel.api.exception.SessionMissingException;
009import org.slf4j.Logger;
010
011import javax.ws.rs.core.Response;
012import javax.ws.rs.ext.ExceptionMapper;
013import javax.ws.rs.ext.Provider;
014
015import static com.google.common.base.Throwables.getStackTraceAsString;
016import static javax.ws.rs.core.Response.serverError;
017import static org.fcrepo.http.commons.domain.RDFMediaType.TEXT_PLAIN_WITH_CHARSET;
018import static org.slf4j.LoggerFactory.getLogger;
019
020/**
021 * Catch all the exceptions!
022 *
023 * @author lsitu
024 * @author awoods
025 * @author cbeer
026 * @author fasseg
027 */
028@Provider
029public class WildcardExceptionMapper implements
030        ExceptionMapper<Exception>, ExceptionDebugLogging {
031
032    Boolean showStackTrace = false;
033
034    private static final Logger LOGGER =
035        getLogger(WildcardExceptionMapper.class);
036
037    @Override
038    public Response toResponse(final Exception e) {
039        if (e.getCause() instanceof SessionMissingException) {
040            return new SessionMissingExceptionMapper()
041                    .toResponse((SessionMissingException) e.getCause());
042        }
043
044        LOGGER.warn("Unmapped exception", e);
045        return serverError().entity(
046                showStackTrace ? getStackTraceAsString(e) : null).type(TEXT_PLAIN_WITH_CHARSET).build();
047    }
048
049    /**
050     * Set whether the full stack trace should be returned as part of the
051     * error response. This may be a bad idea if the stack trace is exposed
052     * to the public.
053     * @param showStackTrace the boolean value of showing stack trace
054     */
055    public void setShowStackTrace(final Boolean showStackTrace) {
056        this.showStackTrace = showStackTrace;
057    }
058}