001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.http.commons.exceptionhandlers;
017
018import static com.google.common.base.Throwables.getStackTraceAsString;
019import static javax.ws.rs.core.Response.serverError;
020import static org.slf4j.LoggerFactory.getLogger;
021
022import javax.jcr.RepositoryException;
023import javax.ws.rs.core.Response;
024import javax.ws.rs.ext.ExceptionMapper;
025import javax.ws.rs.ext.Provider;
026
027import org.fcrepo.kernel.exception.TransactionMissingException;
028import org.slf4j.Logger;
029
030/**
031 * Catch all the exceptions!
032 *
033 * @author lsitu
034 * @author awoods
035 * @author cbeer
036 * @author fasseg
037 */
038@Provider
039public class WildcardExceptionMapper implements ExceptionMapper<Exception> {
040
041    Boolean showStackTrace = true;
042
043    private static final Logger LOGGER =
044        getLogger(WildcardExceptionMapper.class);
045
046    @Override
047    public Response toResponse(final Exception e) {
048
049        if (e.getCause() instanceof TransactionMissingException) {
050            return new TransactionMissingExceptionMapper()
051                    .toResponse((TransactionMissingException) e.getCause());
052        }
053
054        if ( e.getCause() instanceof RepositoryException) {
055            return new RepositoryExceptionMapper()
056                    .toResponse((RepositoryException)e.getCause());
057        }
058
059        LOGGER.info("Exception intercepted by WildcardExceptionMapper: \n", e);
060        return serverError().entity(
061                showStackTrace ? getStackTraceAsString(e) : null).build();
062    }
063
064    /**
065     * Set whether the full stack trace should be returned as part of the
066     * error response. This may be a bad idea if the stack trace is exposed
067     * to the public.
068     * @param showStackTrace the boolean value of showing stack trace
069     */
070    public void setShowStackTrace(final Boolean showStackTrace) {
071        this.showStackTrace = showStackTrace;
072    }
073}