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.RepositoryException;
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 javax.ws.rs.core.Response.Status.BAD_REQUEST;
016import static javax.ws.rs.core.Response.serverError;
017import static javax.ws.rs.core.Response.status;
018import static org.fcrepo.http.commons.domain.RDFMediaType.TEXT_PLAIN_WITH_CHARSET;
019import static org.slf4j.LoggerFactory.getLogger;
020
021/**
022 * Provide a quasi-useful stacktrace when a generic RepositoryException is caught
023 *
024 * @author awoods
025 */
026@Provider
027public class RepositoryExceptionMapper implements
028                                       ExceptionMapper<RepositoryException>, ExceptionDebugLogging {
029
030    private static final Logger LOGGER = getLogger(RepositoryExceptionMapper.class);
031
032    @Override
033    public Response toResponse(final RepositoryException e) {
034        LOGGER.error("Caught a repository exception", e);
035
036        if (e.getMessage().matches("Error converting \".+\" from String to a Name")) {
037            return status(BAD_REQUEST).entity(e.getMessage()).type(TEXT_PLAIN_WITH_CHARSET).build();
038        }
039
040        return serverError().entity(e.getMessage()).type(TEXT_PLAIN_WITH_CHARSET).build();
041    }
042}