将某些异常排除在报告给 Sentry 之外

Excluding certain exceptions from being reported to Sentry

一个基于 spring-boot 的 Web 服务正在使用 docs 中描述的 Sentry。它工作正常,但不应将某些异常发送到哨兵,例如为了 return 某些请求的 HTTP 状态 410 抛出的异常:

// Kotlin code, but in Java it would be similar.
@ResponseStatus(value = HttpStatus.GONE)
class GoneException(msg: String) : RuntimeException(msg) {
}

如何告诉我的 sentryExceptionResolver 跳过这些异常?

在python中很简单,您只需在配置文件中添加以下代码即可忽略多个异常

ignore_exceptions = [
    'Http404',
    'Http401'
    'django.exceptions.http.Http404',
    'django.exceptions.*',
    ValueError,
]

但是在java中我找不到在sentry.properties中类似的标签,你自己试试看也许你会找到。

##Just give it a try, I didnt test    
ignore.exceptions:
        HTTP 401

您可以在配置class中添加HandlerExceptionResolver并覆盖resolveException方法并手动忽略异常。

@Configuration
public class FactoryBeanAppConfig {
    @Bean
    public HandlerExceptionResolver sentryExceptionResolver() {
        return new SentryExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request,
                    HttpServletResponse response,
                    Object handler,
                    Exception ex) {
                Throwable rootCause = ex;

                while (rootCause .getCause() != null && rootCause.getCause() != rootCause) {
                    rootCause = rootCause.getCause();
                }

                if (!rootCause.getMessage().contains("HTTP 401")) {
                    super.resolveException(request, response, handler, ex);
                }
                return null;
            }   

        };
    }

    @Bean
    public ServletContextInitializer sentryServletContextInitializer() {
        return new SentryServletContextInitializer();
    }
}