From c31ecc6b2732ce0ee899554b169d666b2830e9c5 Mon Sep 17 00:00:00 2001 From: Isa Goksu Date: Fri, 7 Dec 2012 12:58:09 -0800 Subject: [PATCH] Enhanced the readme file a bit --- README.md | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 68d5fb9..0c73486 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,49 @@ # spring-restful-exception-handler -### An annotation for the Spring framework to handle HTTP responses for custom exceptions. + +An annotation for the Spring framework to handle HTTP responses for custom exceptions. ## How to use spring-restful-exception-handler + Under PROJECT/resources create a file called *error.template*. Inside this file, place the formatted error template you want to return when a custom exception is thrown. If no custom template is given, the following default template will be used: -``` %s ``` +```xml + + %s +``` -Annotate the custom exception class with `@Exception(*httpStatus*, *contentType*)`. -The defaults are `httpStatus = HttpStatus.INTERNAL_SERVER_ERROR` and `contentType = MediaType.APPLICATION_XML_VALUE`. +Annotate the custom exception class 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 +@ExceptionHandler(httpStatus = HttpStatus.NOT_FOUND, contentType = MediaType.APPLICATION_XML_VALUE) +public class MyCustomException extends Exception { + public MyCustomException(final String message) { + super(message); + } +} +``` The custom message is taken from the custom annotation class itself, so any parameters you'd like to insert need to be handled there. -Make sure to add `` to your XML. +Make sure to add following to your servlet XML: -And that's it! +```xml + +``` +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 want to override, make sure you have `error.template` in your classpath with `%s` for the message placeholder. An example for a `error.template` file in your classpath for a json response: +```json +{ + "message": "%s" +} + +And now you need to make sure that your exceptions are returning `json` content type. + +```java +@ExceptionHandler(httpStatus = HttpStatus.CONFLICT, contentType = MediaType.APPLICATION_JSON_VALUE) +public class MyCustomException extends Exception { + public MyCustomException(final String message) { + super(message); + } +} +```