15 Commits

Author SHA1 Message Date
raychatter
72a89f2b4e [maven-release-plugin] prepare for next development iteration 2013-01-16 23:07:02 -08:00
raychatter
8a4f4b59db [maven-release-plugin] prepare release spring-restful-exception-handler-2.0.1 2013-01-16 23:06:54 -08:00
raychatter
572053174e Refactored and updated pom to version 2.0.1 2013-01-16 18:07:05 -08:00
raychatter
bca69232cb Added ExceptionUtils for getThrowableList 2013-01-16 17:20:05 -08:00
raychatter
65640be661 [maven-release-plugin] prepare release spring-restful-exception-handler-1.1.4 2013-01-15 15:28:34 -08:00
raychatter
61dae14384 Minor change to README 2013-01-15 14:49:51 -08:00
raychatter
c579b866c6 Reorganized README 2013-01-15 14:47:28 -08:00
raychatter
a099e1f8c9 Updated README to reflect new bean properties useGetCause and useHandledExceptionMessage 2013-01-15 14:35:29 -08:00
raychatter
95fef7d449 Made useGetCause and useHandledExceptionMessage bean properties 2013-01-15 14:15:11 -08:00
raychatter
7f00ffbbe9 [maven-release-plugin] prepare for next development iteration 2013-01-06 23:34:00 -08:00
raychatter
121af77b49 [maven-release-plugin] prepare release spring-restful-exception-handler-1.1.3 2013-01-06 23:33:55 -08:00
raychatter
c9f5121992 Added snapshot 2013-01-06 23:33:30 -08:00
raychatter
c052294254 [maven-release-plugin] prepare for next development iteration 2013-01-06 16:59:58 -08:00
raychatter
f6a1e54f19 [maven-release-plugin] prepare release spring-restful-exception-handler-1.1.2 2013-01-06 16:59:51 -08:00
raychatter
d482a60153 [maven-release-plugin] prepare for next development iteration 2013-01-06 16:03:23 -08:00
4 changed files with 133 additions and 36 deletions

View File

@@ -1,11 +1,28 @@
# spring-restful-exception-handler
An annotation for the Spring framework to handle HTTP responses for custom exceptions. The way it works is you have to change the default exception resolver for Spring to our custom exception resolver by modifying your servlet xml file for Spring:
An annotation for the Spring framework to handle HTTP responses for custom exceptions.
### Bean Setup and Properties:
The way it works is you have to change the default exception resolver for Spring to our custom exception resolver by modifying your servlet xml file for Spring:
```xml
<bean id="exceptionResolver" class="com.github.raychatter.AnnotationHandler" />
<bean id="exceptionResolver" class="com.github.raychatter.AnnotationHandler">
<property name="useHandledExceptionMessage" value="true"/>
<property name="useGetCause" value="true"/>
</bean>
```
There are two boolean properties that can be set within the spring-restful-exception-handler bean:
`useGetCause` (true by default)
If an unannotated exception is thrown and `useGetCause` is true, the spring-restful-exception-handler will call `getCause()` on the exception until the first annotated exception is found. Provided there is no annotated exception or `useGetcause` is set to false, the default httpStatus and contentType will be used with the thrown exception.
`useHandledExceptionMessage` (true by default)
Sometimes it is useful to give the user a "higher level" exception response message than the one associated with the handled (annotated) exception. When `useHandledExceptionMessage` is true (which is the default setting), the message returned will be that from the annotated exception. If this property or `useGetCause` is set to false or there is no annotated exception, the message used will be from the thrown exception.
### Annotate the Custom Exception Class:
After overriding the exception resolving mechanism, just annotate the custom exception classes with `@ExceptionHandler(*httpStatus*, *contentType*)`. The defaults are `httpStatus = HttpStatus.INTERNAL_SERVER_ERROR` and `contentType = MediaType.APPLICATION_XML_VALUE`. So an example exception class would be:
```java
@@ -19,7 +36,11 @@ public class MyCustomException extends Exception {
The custom message is taken from the custom annotation class itself, so any parameters you'd like to insert need to be handled there.
And that's it! Just keep in mind that the exception handler will take care of all the exceptions and by default it will return `Internal Server Error` with an `XML` body described above. If you don't specify any custom template for your error responses, following error template will be used by default:
And that's it! Just keep in mind that the exception handler will take care of all the exceptions and by default it will return `Internal Server Error` with an `XML` body described above.
### Error Response Template:
If you don't specify any custom template for your error responses, following error template will be used by default:
```xml
<?xml version="1.0" encoding="UTF-8"?>
@@ -47,6 +68,4 @@ public class MyCustomException extends Exception {
}
```
### Note:
If an unannotated exception is thrown, the spring-restful-exception-handler will call `getCause()` on the exception until the first annotated exception is found. Provided there is no annotated exception, the default httpStatus and contentType will be used.
And that's it!

View File

@@ -18,7 +18,7 @@
<inceptionYear>2012</inceptionYear>
<groupId>com.github.raychatter</groupId>
<artifactId>spring-restful-exception-handler</artifactId>
<version>1.1.1</version>
<version>2.0.2-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
@@ -66,7 +66,7 @@
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
</dependency>
</dependencies>
<build>
@@ -232,7 +232,7 @@
<connection>scm:git:git@github.com:raychatter/spring-restful-exception-handler.git</connection>
<developerConnection>scm:git:git@github.com:raychatter/spring-restful-exception-handler.git</developerConnection>
<url>git@github.com:raychatter/spring-restful-exception-handler.git</url>
<tag>spring-restful-exception-handler-1.1.1</tag>
<tag>spring-restful-exception-handler-1.1.4</tag>
</scm>
<issueManagement>

View File

@@ -18,18 +18,32 @@ public class AnnotationHandler implements HandlerExceptionResolver {
protected static final String USER_TEMPLATE = "error.template";
protected static final String DEFAULT_TEMPLATE = "defaults/default.template";
private static final String UTF_8 = "UTF-8";
private static final String DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_XML_VALUE;
private static final int DEFAULT_STATUS_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();
private boolean useHandledExceptionMessage = true; //use the message from the annotated exception
private boolean useGetCause = true;
public void setUseHandledExceptionMessage(boolean flag) {
useHandledExceptionMessage = flag;
}
public void setUseGetCause(boolean flag) {
useGetCause = flag;
}
@Override
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception thrownException) {
Exception rootException = getAnnotatedException(thrownException, thrownException.getCause());
final ExceptionHandler annotation = getAnnotationFrom(rootException);
final Exception handledException = getHandledException(thrownException);
final ExceptionHandler annotation = getAnnotationFrom(handledException);
final Exception messageException = getMessageException(thrownException, handledException);
try {
if (annotation == null) {
rootException.printStackTrace();
return respondWithDefault(rootException, response);
handledException.printStackTrace();
return respondWithDefault(messageException, response);
}
return handleException(annotation, rootException, response);
return handleException(annotation, messageException, response);
} catch (IOException e) {
// potentially something went wrong in the response itself
e.printStackTrace();
@@ -38,33 +52,49 @@ public class AnnotationHandler implements HandlerExceptionResolver {
return new ModelAndView();
}
protected ModelAndView handleException(final ExceptionHandler annotation, final Exception thrownException, final HttpServletResponse response) throws IOException {
protected Exception getHandledException(final Exception thrownException) {
if(useGetCause) {
return getAnnotatedException(thrownException);
}
return thrownException;
}
// This only matters if the user decides to use getCause
protected Exception getMessageException(final Exception thrownException, final Exception annotatedException) {
if(useHandledExceptionMessage) {
return annotatedException;
}
return thrownException;
}
protected ModelAndView handleException(final ExceptionHandler annotation, final Exception handledException, final HttpServletResponse response) throws IOException {
response.setContentType(annotation.contentType());
response.setStatus(annotation.httpStatus().value());
try {
final String message = formatMessage(thrownException);
final String message = formatMessage(handledException);
response.getWriter().write(message);
} catch (IOException e) {
return respondWithDefault(thrownException, response);
return respondWithDefault(handledException, response);
}
return new ModelAndView();
}
protected ModelAndView respondWithDefault(final Exception thrownException, final HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_XML_VALUE);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.getWriter().write(formatDefaultMessage(thrownException));
protected ModelAndView respondWithDefault(final Exception handledException, final HttpServletResponse response) throws IOException {
response.setContentType(DEFAULT_CONTENT_TYPE);
response.setStatus(DEFAULT_STATUS_CODE);
response.getWriter().write(formatDefaultMessage(handledException));
return new ModelAndView();
}
protected Exception getAnnotatedException(Exception thrownException, Throwable causedException) {
if(getAnnotationFrom(thrownException) != null || causedException == null) {
return thrownException;
protected Exception getAnnotatedException(Exception exception) {
Throwable causedException = exception.getCause();
if(getAnnotationFrom(exception) != null || causedException == null) {
return exception;
} else {
return getAnnotatedException((Exception) causedException, causedException.getCause());
return getAnnotatedException((Exception) causedException);
}
}
@@ -72,12 +102,12 @@ public class AnnotationHandler implements HandlerExceptionResolver {
return exception.getClass().getAnnotation(ExceptionHandler.class);
}
protected String formatMessage(final Exception thrownException) throws IOException {
return String.format(readTemplate(), thrownException.getMessage());
protected String formatMessage(final Exception handledException) throws IOException {
return String.format(readTemplate(), handledException.getMessage());
}
protected String formatDefaultMessage(final Exception thrownException) throws IOException {
return String.format(readDefaultTemplate(), thrownException.getMessage());
protected String formatDefaultMessage(final Exception handledException) throws IOException {
return String.format(readDefaultTemplate(), handledException.getMessage());
}
protected String readTemplate() throws IOException {

View File

@@ -12,6 +12,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
@@ -239,7 +240,6 @@ public class AnnotationHandlerTest {
final AnnotationHandler sut = spy(new AnnotationHandler());
doReturn(new ModelAndView()).when(sut).handleException(mockAnnotation, expectedException, mockResponse);
doReturn(expectedException).when(sut).getAnnotatedException(expectedException, expectedException.getCause());
doReturn(mockAnnotation).when(sut).getAnnotationFrom(expectedException);
final ModelAndView view = sut.resolveException(null, mockResponse, null, expectedException);
@@ -247,6 +247,30 @@ public class AnnotationHandlerTest {
verify(sut).handleException(mockAnnotation, expectedException, mockResponse);
}
@Test public void getMessageException_ShouldReturnHandledException_WhenUseMessageExceptionIsTrue() throws Exception {
final TestExceptionWithNoAnnotationAttributes expectedException = new TestExceptionWithNoAnnotationAttributes("");
final TestExceptionWithNotFoundStatusCode thrownException = new TestExceptionWithNotFoundStatusCode();
final AnnotationHandler sut = spy(new AnnotationHandler());
sut.setUseHandledExceptionMessage(true);
Exception messageException = sut.getMessageException(thrownException, expectedException);
assertEquals(expectedException, messageException);
}
@Test public void getMessageException_ShouldReturnThrownException_WhenUseMessageExceptionIsFalse() throws Exception {
final TestExceptionWithXmlContentType annotatedException = new TestExceptionWithXmlContentType();
final TestExceptionWithNoAnnotation expectedException = new TestExceptionWithNoAnnotation("");
final AnnotationHandler sut = spy(new AnnotationHandler());
sut.setUseHandledExceptionMessage(false);
Exception messageException = sut.getMessageException(expectedException, annotatedException);
assertEquals(expectedException, messageException);
}
@Test public void resolveException_ShouldReturnDefaultErrorMessage_WhenUncheckedExceptionIsGiven() throws Exception {
final NullPointerException expectedException = mock(NullPointerException.class);
@@ -255,7 +279,7 @@ public class AnnotationHandlerTest {
when(mockResponse.getWriter()).thenReturn(mockPrinter);
final AnnotationHandler sut = spy(new AnnotationHandler());
when(sut.getAnnotatedException(expectedException, expectedException.getCause())).thenReturn(expectedException);
when(sut.getAnnotatedException(expectedException)).thenReturn(expectedException);
when(sut.getAnnotationFrom(expectedException)).thenReturn(null);
final ModelAndView view = sut.resolveException(null, mockResponse, null, expectedException);
@@ -263,7 +287,7 @@ public class AnnotationHandlerTest {
verify(sut).respondWithDefault(expectedException, mockResponse);
}
@Test public void getAnnotatedException_ShouldReturnOutermostAnnotatedException_WhenThereAreCheckedExceptionsChained() throws Exception {
@Test public void getAnnotatedException_ShouldReturnOutermostAnnotatedException_WhenThereAreCheckedExceptionsChainedAndGetCauseIsTrue() throws Exception {
TestExceptionWithNoAnnotationAttributes mockException = mock(TestExceptionWithNoAnnotationAttributes.class);
doReturn(new TestExceptionWithXmlContentType()).when(mockException).getCause();
@@ -276,10 +300,26 @@ public class AnnotationHandlerTest {
final ModelAndView view = sut.resolveException(null, mockResponse, null, mockException);
Assert.assertTrue(sut.getAnnotatedException(mockException,mockException.getCause()) instanceof TestExceptionWithNoAnnotationAttributes);
Assert.assertTrue(sut.getAnnotatedException(mockException) instanceof TestExceptionWithNoAnnotationAttributes);
}
@Test public void getAnnotatedException_ShouldReturnFirstChainedAnnotatedException_WhenThrownExceptionIsUnannotated() throws Exception {
@Test public void getHandledException_ShouldReturnThrownException_WhenThereAreCheckedExceptionsChainedAndGetCauseIsFalse() throws Exception {
TestExceptionWithNoAnnotationAttributes mockException = mock(TestExceptionWithNoAnnotationAttributes.class);
doReturn(new TestExceptionWithXmlContentType()).when(mockException).getCause();
final ExceptionHandler mockAnnotation = mock(ExceptionHandler.class);
final HttpServletResponse mockResponse = mock(HttpServletResponse.class);
final AnnotationHandler sut = spy(new AnnotationHandler());
when(sut.getAnnotationFrom(mockException)).thenReturn(mockAnnotation);
doReturn(new ModelAndView()).when(sut).handleException(mockAnnotation, mockException, mockResponse);
final ModelAndView view = sut.resolveException(null, mockResponse, null, mockException);
Assert.assertTrue(sut.getAnnotatedException(mockException) instanceof TestExceptionWithNoAnnotationAttributes);
}
@Test public void getHandledException_ShouldReturnFirstChainedAnnotatedException_WhenThrownExceptionIsUnannotatedAndGetCauseIsTrue() throws Exception {
TestExceptionWithNoAnnotation mockException = mock(TestExceptionWithNoAnnotation.class);
TestExceptionWithNoAnnotationAttributes expectedException = new TestExceptionWithNoAnnotationAttributes("");
doReturn(expectedException).when(mockException).getCause();
@@ -291,9 +331,17 @@ public class AnnotationHandlerTest {
when(sut.getAnnotationFrom(expectedException)).thenReturn(mockAnnotation);
doReturn(new ModelAndView()).when(sut).handleException(mockAnnotation, expectedException, mockResponse);
final ModelAndView view = sut.resolveException(null, mockResponse, null, expectedException);
Assert.assertTrue(sut.getHandledException(mockException) instanceof TestExceptionWithNoAnnotationAttributes);
}
Assert.assertTrue(sut.getAnnotatedException(mockException,mockException.getCause()) instanceof TestExceptionWithNoAnnotationAttributes);
@Test public void getHandledException_ShouldReturnThrownException_WhenThrownExceptionIsUnannotatedAndGetCauseIsFalse() throws Exception {
TestExceptionWithNoAnnotation expectedException = new TestExceptionWithNoAnnotation("");
final AnnotationHandler sut = new AnnotationHandler();
sut.setUseGetCause(false);
Exception actualException = sut.getHandledException(expectedException);
Assert.assertTrue(actualException instanceof TestExceptionWithNoAnnotation);
}
}