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 org.fcrepo.kernel.exception.RepositoryRuntimeException;
019
020import org.slf4j.Logger;
021
022import javax.ws.rs.core.Context;
023import javax.ws.rs.core.Response;
024import javax.ws.rs.ext.ExceptionMapper;
025import javax.ws.rs.ext.Provider;
026import javax.ws.rs.ext.Providers;
027
028import static com.google.common.base.Throwables.getStackTraceAsString;
029import static javax.ws.rs.core.Response.serverError;
030import static org.slf4j.LoggerFactory.getLogger;
031
032/**
033 * @author cabeer
034 * @since 9/13/14
035 */
036
037@Provider
038public class RepositoryRuntimeExceptionMapper implements
039        ExceptionMapper<RepositoryRuntimeException> {
040
041    private final Providers providers;
042
043    /**
044     * Get the context Providers so we can rethrow the cause to an appropriate handler
045     * @param providers the providers
046     */
047    public RepositoryRuntimeExceptionMapper(@Context final Providers providers) {
048        this.providers = providers;
049    }
050
051    private static final Logger LOGGER = getLogger(RepositoryExceptionMapper.class);
052
053    @Override
054    public Response toResponse(final RepositoryRuntimeException e) {
055        final Throwable cause = e.getCause();
056        @SuppressWarnings("unchecked")
057        final ExceptionMapper<Throwable> exceptionMapper =
058                (ExceptionMapper<Throwable>) providers.getExceptionMapper(cause.getClass());
059        if (exceptionMapper != null) {
060            return exceptionMapper.toResponse(cause);
061        }
062        LOGGER.warn("Caught repository exception: {}", e.getMessage());
063        return serverError().entity(getStackTraceAsString(e)).build();
064    }
065}