I want to customize DefaultHandlerExceptionResolver
in my Spring Boot application but custom implementation was never reached when exception was occurred.
build.gradle
buildscript {
ext {
springBootVersion = '2.1.1.RELEASE'
}
repositories {
mavenCentral()
}
}
plugins {
id 'java'
id 'org.springframework.boot' version '2.1.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.6.RELEASE'
id 'io.franzbecker.gradle-lombok' version '1.14'
}
lombok {
version = '1.18.4'
sha256 = ""
}
group = 'ua.com.javaman'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
}
Application.java
@SpringBootApplication
@RestController
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@ResponseBody
@PostMapping("/mouse")
public Mouse postMouse(@Valid Mouse mouse) {
// mouse creation logic
return mouse;
}
@Bean
public HandlerExceptionResolver customHandlerExceptionResolver() {
return new CustomExceptionHandlerResolver();
}
}
Mouse.java
@Value
public class Mouse {
private final Long id;
@NotEmpty
@Min(2)
private final String name;
}
CustomExceptionHandlerResolver.java
public class CustomExceptionHandlerResolver extends DefaultHandlerExceptionResolver {
@Override
protected ModelAndView handleBindException(
BindException ex, HttpServletRequest request, HttpServletResponse response, @Nullable Object handler
) throws IOException {
System.out.println("In CustomExceptionHandlerResolver");
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return new ModelAndView();
}
}
Package structure
.
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── LICENSE
├── README.md
├── settings.gradle
└── src
└── main
└── java
└── ua
└── com
└── javaman
└── exception_handling
├── Application.java
├── CustomExceptionHandlerResolver.java
└── Mouse.java
When I invoke application with wrong values for Mouse
entity, for example,
POST localhost:8080/mouse?name=1
than handleBindException()
method in DefaultHandlerExceptionResolver
is invoked but not in my CustomExceptionHandlerResolver
.
How can I handle BindException
with my CustomExceptionHandlerResolver
?
@Component
onCustomExceptionHandlerResolver
– Thermoelectric@Component
have not resolved my problem – Cartercarteret