简体   繁体   中英

How to customize DefaultHandlerExceptionResolver logic?

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 ?

SpringBoot 's auto configuration will always create a bunch of exception handlers by default which one of them is DefaultHandlerExceptionResolver at order 0 (lower value has the higher priority) . Your handler by default will has lower priority than these default , so it will not be invoked as the exception is already handled by the default.

You can implement your configuration class with WebMvcConfigurer and override extendHandlerExceptionResolvers() to modify the default settings. The idea is to find out the DefaultHandlerExceptionResolver instance and replace it with yours.

But a better idea is to define your CustomExceptionHandlerResolver with @ControllerAdvice , which make sure that you will not mess up with the default settings while still add the customised behaviour that your want (ie use your logic to handle BindException ) :

@Component
@ControllerAdvice
public class CustomExceptionHandlerResolver {

    @ExceptionHandler(value= BindException.class)
    @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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM