不从@Service 的方法中抛出异常

Not throwing exception from a @Service's methods

我有一个通知服务(我可以控制这个class)。

如果有unchecked exception,我不想抛。而是想以特定方式记录它。

我可以在每个方法的实现中直接使用 try catch 块,但我想在这里寻找一些魔法

有没有通用的方法可以通过 Spring 来处理?


更新: AOP也是一种方法。例如:https://dzone.com/articles/handling-exceptions-using-springs-aop 还有其他直接实现吗?

这是我的要求,但我找不到与此相关的任何信息。

我在处理从休息服务调用多个 api 时遇到了类似的问题,我想在发生错误时提供回退实现。我的 Aspect 比我在这里举的例子要多。

服务

@Service
public class SuspiciousService {
    final Random random = new Random();

    public String beSuspicious() {
        final boolean value = random.nextBoolean();
        if (value) {
            throw new IllegalStateException("Exception occured for: " + value);
        }
        return "I am not suspicious";
    }
}

随机抛出错误的示例服务。

控制器

@RestController
@RequestMapping("/is-suspicious")
@AllArgsConstructor
public class SampleController {
    private final SuspiciousService suspiciousService;

    @GetMapping
    public Map<String, String> get() {
        return Map.of("isSuspicious", suspiciousService.beSuspicious());
    }

}

调用此服务的控制器。

最后,Around Aspect 捕获此异常并提供示例响应。

@Aspect
@Component
@Order(2)
public class AspectAroundSuspiciousService {

    @Around("execution(* in.silentsudo.sprintbootresttemplate.SuspiciousService.beSuspicious(..))")
    public Object parallelExecuteBeforeAndAfterCompose(ProceedingJoinPoint point) throws Throwable {
        try {
            return point.proceed();
        } catch (RuntimeException re) {
            return "Yes, I am suspicious";
        }
    }

}

另一种方法是,如果您使用的是 ByteBuddy,则可以在抛出异常的方法中添加注释

@Advice.OnMethodExit(onThrowable = RuntimeException.class)

并且有一个 ExceptionHandler 来处理这个

  @ExceptionHandler
    private String suspiciousRuntimeException(RuntimeException exception) {
        return "Yes, I am suspicious from ex handler, error: " + exception.getMessage();
    }

我选择 aspect 而不是 bytebuddy 的原因很简单,因为我正在处理 api 异常的阶梯,因为这个实现通常会捕获来自 service#method

的 RuntimeException