001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.processor;
018
019import java.io.*;
020
021import org.apache.juneau.commons.reflect.*;
022import org.apache.juneau.http.*;
023import org.apache.juneau.http.header.*;
024import org.apache.juneau.http.response.*;
025import org.apache.juneau.rest.server.*;
026import org.apache.juneau.rest.server.rrpc.*;
027
028/**
029 * Response handler for {@link Throwable} objects.
030 *
031 * <p>
032 * Adds a <c>Thrown</c> header (exception class name and message) to the response and returns <c>0</c> so that the
033 * processor chain can continue.
034 *
035 * <p>
036 * The header is only added when the exception was deliberately thrown for a client audience (a
037 * {@link BasicHttpException} or a class annotated with {@link Response @Response}), when
038 * {@link RestContext#isRenderResponseStackTraces() renderResponseStackTraces} is enabled, or when the operation is an
039 * RRPC dispatch target (the {@code @Remote} client relies on the header to reconstruct the exception type).
040 * Any other, unplanned exception keeps its class name and message out of the response by default.
041 *
042 * <h2 class='section'>See Also:</h2><ul>
043 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ResponseProcessors">Response Processors</a>
044 * </ul>
045 */
046public class ThrowableProcessor implements ResponseProcessor {
047
048   @Override /* Overridden from ResponseProcessor */
049   public int process(RestOpSession opSession) throws IOException {
050      RestResponse res = opSession.getResponse();
051      Throwable t = res.getContent(Throwable.class);
052      if (t != null && isExposable(opSession, t))
053         res.addHeader(Thrown.of(t));
054      return NEXT; // Continue processing as bean.
055   }
056
057   private static boolean isExposable(RestOpSession opSession, Throwable t) {
058      return t instanceof BasicHttpException
059         || ClassInfo.of(t).hasAnnotation(Response.class)
060         || opSession.getRestContext().isRenderResponseStackTraces()
061         || opSession.getContext() instanceof RrpcRestOpContext;
062   }
063}