获取 Java 中的所有异常并远程发送

2022-09-04 06:49:37

我有一个巨大的Java应用程序。我想拦截所有Java异常并通过电子邮件发送它们。我无法在任何地方添加用于发送代码的代码,因此是否可以使用例如Aspect将异常拦截到低级类中并获取异常内容?try-catch

或者有没有办法覆盖一些内部Java类并获取异常有效负载?

什么是可能的?


答案 1

您可以使用spring-aop的建议。@AfterThrowing

@Aspect
@Component
public class MailExceptionAspect {

    @AfterThrowing(value="execution(* com.example..*.*(..))", throwing="ex" )
    public void mailAfterThrowing(Throwable ex) {
        // do something to send an email
    }
}

这将截获包中所有未处理的异常。请注意,无法在应用程序中处理(捕获)的异常被截获。com.example

另一种解决方案是使用应用程序的日志记录框架。许多框架,如logback,log4j提供可以通过电子邮件发送日志的内置配置。


答案 2

看看Spring的@ControllerAdvice注释。我们用它来做我认为你想要的。我们有一个Web应用程序,它有许多s和s。这将发送一封电子邮件,其中包含有关在这些控制器中的任何方法引发错误时触发该请求的请求的许多详细信息。我们不会为 发送电子邮件,因为当用户在处理请求时关闭浏览器时,通常会发生这种情况。@Controller@RestControllerClientAbortExceptions

@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private static final String ERROR_EMAIL_ADDRESS = "foo@bar.com";
    private static final String APPLICATION_ERROR_SUBJECT = "Foo Error Occurred";
    private static final String USER_AGENT = "user-agent";

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity defaultErrorHandler(final HttpServletRequest request, final Principal principal, final Exception e) {
        final String userTime = principal.getName() + " triggered an error at " + new Date();
        final String userAgent = "User-Agent: " + StringUtils.trimToEmpty(request.getHeader(USER_AGENT));
        final String url = "URL: " + StringUtils.trimToEmpty(request.getRequestURL().toString());
        final String httpMethod = "HTTP method: " + request.getMethod();

        final StringBuilder emailSb = new StringBuilder();
        emailSb.append(userTime).append("\n");
        emailSb.append(userAgent).append("\n");
        emailSb.append(url).append("\n");
        emailSb.append(httpMethod).append("\n");

        if(e instanceof ClientAbortException){
            logger.debug("Not sending email for socketExceptions");
        }else {
            emailSb.append(ExceptionUtils.getStackTrace(e));
            //just a simple util class we use to send emails with javax.mail api
            EmailUtil.sendEmail(ERROR_EMAIL_ADDRESS, ERROR_EMAIL_ADDRESS, APPLICATION_ERROR_SUBJECT,
                                emailSb.toString());
        }

        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

推荐