GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Spring Lemon Exceptions Guide Spring Lemon Exceptions Guide
Sanjay Patel edited this page
The For example, when a {
"exceptionId": "ConstraintViolationException",
"error": "Unprocessable Entity",
"message": "Validation Error",
"status": 422,
"errors": [
{
"field": "user.captchaResponse",
"code": "{com.naturalprogrammer.spring.wrong.captcha}",
"message": "Looks like you are a robot! Please try again."
},
{
"field": "user.password",
"code": "{com.naturalprogrammer.spring.blank.password}",
"message": "Password needed"
}
]
}As we'll see in this guide, spring-lemon-exceptions is quite extensible and customizable to easily take care of sophisticated exception handling and validation needs. Add the following to your pom.xml (or the equivalent to build.gradle): <dependencies> <dependency> <groupId>com.naturalprogrammer.spring-lemon</groupId> <artifactId>spring-lemon-exceptions</artifactId> <version>${spring-lemon.version}</version><!-- See https://github.com/naturalprogrammer/spring-lemon/releases for the latest release --> </dependency> ... </dependencies> <repositories> <repository> <id>naturalprogrammer</id> <url>https://naturalprogrammer.github.io/mvn-repository</url> </repository> ... </repositories>
public class ErrorResponse { private String exceptionId; private String error; private String message; private Integer status; private Collection<LemonFieldError> errors; ... } Noticed public class LemonFieldError { // Name of the field having error. Null in case of a global form level error. private String field; // Error code. Typically the I18n message-code. private String code; // Error message private String message; ... } To translate exceptions to ErrorResponses, spring-lemon-exceptions would use exception handlers. Exception handlers are classes inheriting
public abstract class AbstractExceptionHandler<T extends Throwable> { private Class<?> exceptionClass; public AbstractExceptionHandler(Class<?> exceptionClass) { this.exceptionClass = exceptionClass; } public Class<?> getExceptionClass() { return exceptionClass; } protected String getExceptionId(T ex) { return LexUtils.getExceptionId(ex); } protected String getMessage(T ex) { return ex.getMessage(); } protected HttpStatus getStatus(T ex) { return null; } protected Collection<LemonFieldError> getErrors(T ex) { return null; } public ErrorResponse getErrorResponse(T ex) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setExceptionId(getExceptionId(ex)); errorResponse.setMessage(getMessage(ex)); HttpStatus status = getStatus(ex); if (status != null) { errorResponse.setStatus(status.value()); errorResponse.setError(status.getReasonPhrase()); } errorResponse.setErrors(getErrors(ex)); return errorResponse; } } The Exception handlers are configured as Spring beans so that Spring Lemon finds them. So, don't forget to annotate your custom handlers with How does Spring Lemon know which handler to use for an exception? Did you notice the When the application starts, Spring Lemon has an Then, when an exception is caught, When ErrorResponseComposer finds multiple handlers for the same exception type, it picks the one with highest precedence. So, if you want to override a built-in handler, define yours with a higher precedence, as below: @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class MyMultiErrorExceptionHandler extends AbstractExceptionHandler<MultiErrorException> { ... } All built-in handlers are defined as
So, when an exception occurs in our application, we should
Catching the exception and sending the composed response is not a part of this Did you notice the ExceptionMaker interface looks as below: @FunctionalInterface public interface ExceptionIdMaker { String make(Throwable t); } A default implementation bean is provided in @Bean @ConditionalOnMissingBean(ExceptionIdMaker.class) public ExceptionIdMaker exceptionIdMaker() { log.info("Configuring ExceptionIdMaker"); return ex -> { if (ex == null) return null; return ex.getClass().getSimpleName(); }; } As you see, it'd return the name of the class. To override it, just provide your own ExceptionIdMaker bean. spring-lemon-exception comes with a couple of exception classes that you can use in your code:
In fact, these are well used in other modules of Spring Lemon.
new MultiErrorException() .exceptionId("ConstraintViolationException") // optional; default is MultiErrorException .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) // optional; default is UNPROCESSABLE_ENTITY .validateField("fieldA", fieldA != 0, "msg1") // accumulates a field level error .validateField("fieldA", fieldA < 10000, "msg2", 10000) // accumulates another field level error .validateField("fieldB", fieldB.indexOf("foo") != -1, "msg3") // accumulates another field level error .validate(form.isOk(), "msg4") // accumulates a form level error .validateBean("userForm", form) // accummulates JSR-303 bean validation constraint violations .validationGroups(groups...) // sets validation groups for forthcoming bean validations .validateBean("profileForm", profileForm) // accummulates JSR-303 bean validation constraint violations, applying above groups .go(); // throws the exception if there are any errors accummulated To make it look a bit nicer,
In summary, MultiErrorException is a single powerful tool to validate multiple beans and arbitrary conditions at one go. If you want to use a single and simple validation pattern, just use this. Throw the Spring Lemon already comes with a rich set of exception handlers:
Depending on the modules you are using, some or all of these would already be available to you. However, for the exception types not covered above, or for overriding any of the above handlers, you may need to code your own handlers. To know how exactly to code your own handlers, let's take an example from Spring Lemon itself: @Component @Order(Ordered.LOWEST_PRECEDENCE) public class UsernameNotFoundExceptionHandler extends AbstractExceptionHandler<UsernameNotFoundException> { public UsernameNotFoundExceptionHandler() { super(UsernameNotFoundException.class); log.info("Created"); } @Override public HttpStatus getStatus(UsernameNotFoundException ex) { return HttpStatus.UNAUTHORIZED; } } Points to note:
For more examples, have a look at the other handlers in Spring Lemon.
Our general recommendations on validating request data would be:
The last one is the most powerful pattern. If you want to use a single pattern, use just that. Clone this wiki locally |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |