|
| 1 | +package example; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import javax.servlet.ServletException; |
| 6 | +import javax.servlet.http.HttpServletRequest; |
| 7 | +import javax.servlet.http.HttpServletResponse; |
| 8 | + |
| 9 | +import ca.uhn.fhir.rest.method.RequestDetails; |
| 10 | +import ca.uhn.fhir.rest.server.Constants; |
| 11 | +import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; |
| 12 | +import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; |
| 13 | + |
| 14 | +//START SNIPPET: interceptor |
| 15 | +public class RequestExceptionInterceptor extends InterceptorAdapter |
| 16 | +{ |
| 17 | + |
| 18 | + @Override |
| 19 | + public boolean handleException(RequestDetails theRequestDetails, Throwable theException, HttpServletRequest theServletRequest, |
| 20 | + HttpServletResponse theServletResponse) throws ServletException, IOException { |
| 21 | + |
| 22 | + // If the exception is a built-in type, it defines the correct status |
| 23 | + // code to return. Otherwise default to 500. |
| 24 | + if (theException instanceof BaseServerResponseException) { |
| 25 | + theServletResponse.setStatus(((BaseServerResponseException) theException).getStatusCode()); |
| 26 | + } else { |
| 27 | + theServletResponse.setStatus(Constants.STATUS_HTTP_500_INTERNAL_ERROR); |
| 28 | + } |
| 29 | + |
| 30 | + // Provide a response ourself |
| 31 | + theServletResponse.setContentType("text/plain"); |
| 32 | + theServletResponse.getWriter().append("Failed to process!"); |
| 33 | + theServletResponse.getWriter().close(); |
| 34 | + |
| 35 | + // Since we handled this response in the interceptor, we must return false |
| 36 | + // to stop processing immediately |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | +} |
| 42 | +//END SNIPPET: interceptor |
0 commit comments