Spring Boot中如何为不同控制器配置专属@ExceptionHandler?
为不同控制器配置专属@ExceptionHandler的方案
方案一:拆分控制器为独立类(推荐,代码清晰易维护)
将两个控制器分别写成独立的类,在每个控制器类内部编写对应的@ExceptionHandler,这样处理器只会处理当前控制器方法抛出的异常。
控制器1代码
@RestController @RequestMapping("/controller1") public class Controller1 { @GetMapping("/test") public String test1() { // 抛出控制器1专属异常 throw new CustomException1("来自控制器1的异常"); } // 仅处理Controller1中抛出的CustomException1 @ExceptionHandler(CustomException1.class) public ResponseEntity<String> handleController1Exception(CustomException1 ex) { return ResponseEntity.badRequest().body("处理控制器1异常:" + ex.getMessage()); } }
控制器2代码
@RestController @RequestMapping("/controller2") public class Controller2 { @GetMapping("/test") public String test2() { // 抛出控制器2专属异常 throw new CustomException2("来自控制器2的异常"); } // 仅处理Controller2中抛出的CustomException2 @ExceptionHandler(CustomException2.class) public ResponseEntity<String> handleController2Exception(CustomException2 ex) { return ResponseEntity.badRequest().body("处理控制器2异常:" + ex.getMessage()); } }
自定义专属异常类
为两个控制器分别定义异常类,确保异常能被对应处理器精准捕获:
// 控制器1专属异常 public class CustomException1 extends RuntimeException { public CustomException1(String message) { super(message); } } // 控制器2专属异常 public class CustomException2 extends RuntimeException { public CustomException2(String message) { super(message); } }
方案二:控制器放在同一个类中(不推荐,可读性差)
如果一定要把两个控制器放在同一个类里,可以将它们定义为静态内部类,再通过@ControllerAdvice指定专属的异常处理器:
public class CombinedControllers { // 控制器1内部类 @RestController @RequestMapping("/controller1") public static class Controller1 { @GetMapping("/test") public String test1() { throw new CustomException1("来自控制器1的异常"); } } // 控制器2内部类 @RestController @RequestMapping("/controller2") public static class Controller2 { @GetMapping("/test") public String test2() { throw new CustomException2("来自控制器2的异常"); } } // 仅处理Controller1的异常 @ControllerAdvice(assignableTypes = Controller1.class) public static class Controller1ExceptionHandler { @ExceptionHandler(CustomException1.class) public ResponseEntity<String> handleException(CustomException1 ex) { return ResponseEntity.badRequest().body("处理控制器1异常:" + ex.getMessage()); } } // 仅处理Controller2的异常 @ControllerAdvice(assignableTypes = Controller2.class) public static class Controller2ExceptionHandler { @ExceptionHandler(CustomException2.class) public ResponseEntity<String> handleException(CustomException2 ex) { return ResponseEntity.badRequest().body("处理控制器2异常:" + ex.getMessage()); } } }
关键说明
- 方案一中,控制器内部的
@ExceptionHandler只会捕获当前控制器方法抛出的指定异常,不会影响其他控制器。 - 自定义专属异常是为了让处理器精准匹配,避免不同控制器的异常被混淆处理。
内容的提问来源于stack exchange,提问作者Anita
相关产品推荐
相关产品推荐

