如何从Resilience4j @CircuitBreaker的fallback方法返回自定义异常?
在Resilience4j @CircuitBreaker的fallback方法中返回自定义BadRequestException的实现方案
要在fallback方法中实现返回自定义BadRequestException的效果,核心是在fallback方法中抛出该异常,利用其@ResponseStatus注解让Spring自动转换为HTTP 400响应,而非直接返回ResponseEntity。以下是两种可行实现方式:
方式一:保持BadRequestException为Checked Exception
修改fallback方法的声明,添加异常抛出声明,直接抛出自定义异常:
@RestController public class Endpoint { @CircuitBreaker(name = "createAccount", fallbackMethod = "fallbackGetListValues") @GetMapping("/greeting") public ResponseEntity<?> greeting() { try { throw new Exception("test"); } catch (Exception e) { throw new RuntimeException(e); } } // 声明抛出BadRequestException,Spring会自动处理为400响应 public ResponseEntity<?> fallbackGetListValues(Exception e) throws BadRequestException { throw new BadRequestException(); } }
自定义异常类保持不变:
@ResponseStatus( value = HttpStatus.BAD_REQUEST, reason = "You got a invalid request." ) public class BadRequestException extends Exception{ }
方式二:将BadRequestException改为RuntimeException
将自定义异常改为继承RuntimeException,无需在fallback方法中声明抛出,代码更简洁:
修改自定义异常类:
@ResponseStatus( value = HttpStatus.BAD_REQUEST, reason = "You got a invalid request." ) public class BadRequestException extends RuntimeException{ // 改为继承RuntimeException }
修改fallback方法:
@RestController public class Endpoint { @CircuitBreaker(name = "createAccount", fallbackMethod = "fallbackGetListValues") @GetMapping("/greeting") public ResponseEntity<?> greeting() { try { throw new Exception("test"); } catch (Exception e) { throw new RuntimeException(e); } } public ResponseEntity<?> fallbackGetListValues(Exception e) { throw new BadRequestException(); // 直接抛出,无需声明 } }
补充:忽略特定异常(对应原Hystrix的ignoreExceptions)
如果需要让BadRequestException不触发断路器(和原Hystrix的ignoreExceptions效果一致),可以在@CircuitBreaker注解中配置:
@CircuitBreaker( name = "createAccount", fallbackMethod = "fallbackGetListValues", ignoreExceptions = {BadRequestException.class} // 忽略该异常,不触发断路器 )
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

