sentry 和sping boot 主動發送異常消息

Sentry是一家開源公司,提供了一個應用程序監視平臺,可以幫助實時識別問題。

  • 集成jar 包,pom.xml

<dependency>
     <groupId>io.sentry</groupId>
     <artifactId>sentry-spring</artifactId>
      <version>1.7.27</version>
</dependency>

  • 配置sentry(application.yml)

sentry:
  dsn: http://[email protected]:1111/34
  enable: true
  • 配置sentry(application.yml)

package www.omit.omit.common.sentry;

import io.sentry.Sentry;
import io.sentry.SentryClient;
import io.sentry.spring.SentryExceptionResolver;
import io.sentry.spring.SentryServletContextInitializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;

@Configuration
@ConditionalOnProperty(value = "sentry.enable")
public class SentryAutoConfiguration {

    @Value("${sentry.dsn}")
    String dsn;


    @Bean
    public SentryClient sentryClient() {
        return Sentry.init(dsn);
    }

    @Bean
    @ConditionalOnMissingBean(SentryExceptionResolver.class)
    public HandlerExceptionResolver sentryExceptionResolver() {
        return new SentryExceptionResolver();
    }

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

}
  • 到上一步,就可以自動捕獲消息了,但這還不夠,有時候程序捕獲了異常,還需要主動發送消息

package www.omit.omit.common.exception;

import io.sentry.SentryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.annotation.Resource;


/**
 * 這裏是做了一個全局控制器,全局捕獲異常並返回,其他方式也可以,只是一個示例
 */
@ControllerAdvice
public class AcmeControllerAdvice extends ResponseEntityExceptionHandler {
    // 這裏是引入sentry
    @Resource
    SentryClient sentryClient;

    // 捕獲異常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleControllerException(Exception ex) {
        // 這裏是打印異常堆棧信息
        ex.printStackTrace();
        // 因爲消息被捕獲了,不會自動發送異常消息,需要手動捕獲發送給sentry
        sentryClient.sendException(ex);
        // 返回友好的報錯提示,這個可以換成你自己寫的返回類封裝,HashMap格式。
        return ResultUtils.error("參與人數較多,請稍後重試~");
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章