001/*
002 * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.webdav;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026
027import javax.ws.rs.WebApplicationException;
028import javax.ws.rs.core.Response;
029import javax.ws.rs.ext.ExceptionMapper;
030import javax.ws.rs.ext.Provider;
031
032import java.io.PrintWriter;
033import java.io.StringWriter;
034
035/**
036 * Simple error handler to give back a user-readable status, and log it to the console.
037 * <p>
038 * This is a convenience for trouble-shouting.
039 */
040@Provider
041public class ExceptionHandler implements ExceptionMapper<Exception> {
042
043    private static final Log log = LogFactory.getLog(ExceptionHandler.class);
044
045    @Override
046    public Response toResponse(Exception e) {
047        StringWriter sw = new StringWriter();
048        e.printStackTrace(new PrintWriter(sw));
049        int status = 500;
050        // String msg;
051        if (e instanceof WebApplicationException) {
052            status = ((WebApplicationException) e).getResponse().getStatus();
053            if (status < 400 || status >= 500) {
054                log.error("Status = " + status);
055                log.error(e, e);
056            }
057            // msg = "Error " + status + "\n" + e.getMessage() + "\n" + sw;
058        } else {
059            log.error(e, e);
060            // msg = "Error\n\n" + e.getMessage() + "\n\n" + sw;
061        }
062        return Response.status(status).build();
063    }
064
065}