gpt4 book ai didi

java - Spring boot @ExceptionHandler 未捕获子类异常

转载 作者:行者123 更新时间:2023-12-02 01:03:31 26 4
gpt4 key购买 nike

我已经创建了一些用于异常处理的子类。该方法抛出子类异常。我为父类(super class)和子类创建了@ExceptionHandler。但只有当没有对异常的父类(super class)进行处理(handleSuperException(SuperclassExceptionException e))时,才会处理子类异常。 SubClassAException、SubClassBException、SubClassCException 扩展了 SuperclassException 异常。

 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。

最佳答案

无法重现!

这里是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()

关于java - Spring boot @ExceptionHandler 未捕获子类异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60340476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com