Spring boot @ExceptionHandler未捕获子类异常

问题描述 投票:0回答:1

我为异常处理创建了一些子类。该方法引发子类异常。我已经为超类和子类都设置了@ExceptionHandler。但是,只有在不处理异常的超类(handleSuperException(SuperclassExceptionexception e))时,才处理子类异常。 SubClassAException,SubClassBException,SubClassCException扩展了SuperclassExceptionexception。

 public class Controller @PostMapping("/path/") {
       public ResponseEntity<String> method() throws   SuperclassException{
 }
    @ExceptionHandler(SuperclassException.class)   
public ResponseEntity handleSuperException(SuperclassExceptionexception e) {
       //hadle superclass related
    }

 @ExceptionHandler({SubClassAException.class, SubClassBException.class, SubClassCException.class}) 
public ResponseEntity handleSubClassException(SuperclassExceptionexception e) {
//handle more specific
}

但是即使抛出子类异常,它也永远不会处理handleSubClassException。

java spring-boot exception
1个回答
0
投票

无法复制!

这里是Minimal, Reproducible Example,已通过Spring Boot 2.2.0(Spring 5.2.0)测试。

package web.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class FailController {

    @GetMapping("/dmz/fail")
    public String failSuper() {
        throw new SuperclassException("failSuper()");
    }

    @GetMapping("/dmz/failA")
    public String failA() {
        throw new SubClassAException("failA()");
    }

    @GetMapping("/dmz/failB")
    public String failB() {
        throw new SubClassBException("failB()");
    }

    @ExceptionHandler(SuperclassException.class)
    public ResponseEntity<?> handleSuperException(SuperclassException e) {
        return ResponseEntity.badRequest().body("handleSuperException: " + e);
    }

    @ExceptionHandler({SubClassAException.class, SubClassBException.class}) 
    public ResponseEntity<?> handleSubClassException(SuperclassException e) {
        return ResponseEntity.badRequest().body("handleSubClassException: " + e);
    }

}

class SuperclassException extends RuntimeException {
    public SuperclassException(String message) {
        super(message);
    }
}

class SubClassAException extends SuperclassException {
    public SubClassAException(String message) {
        super(message);
    }
}

class SubClassBException extends SuperclassException {
    public SubClassBException(String message) {
        super(message);
    }
}

我正在使用/dmz/,因此Spring Security设置不需要登录。在普通的Spring Boot设置中,当然不需要。

输出(http://localhost:8080/dmz/fail

handleSuperException: web.controller.SuperclassException: failSuper()

输出(http://localhost:8080/dmz/failA

handleSubClassException: web.controller.SubClassAException: failA()

输出(http://localhost:8080/dmz/failB

handleSubClassException: web.controller.SubClassBException: failB()
© www.soinside.com 2019 - 2024. All rights reserved.