Sentry是一家開源公司,提供了一個應用程序監視平臺,可以幫助實時識別問題。
<dependency>
<groupId>io.sentry</groupId>
<artifactId>sentry-spring</artifactId>
<version>1.7.27</version>
</dependency>
sentry:
dsn: http://[email protected]:1111/34
enable: true
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("參與人數較多,請稍後重試~");
}
}