Java Code Examples for io.sentry.Sentry#capture()
The following examples show how to use
io.sentry.Sentry#capture() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Reporter.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
/** * Rejette une exception dans un salon discord. Politique du "posté uniquement une fois" * @param exception Exception à rejeter * @param guild Guilde d'origine de l'erreur * @param channel Salon d'origine de l'erreur * @param user Auteur du message d'origine de l'erreur * @param message Contenu du message à l'origine de l'erreur */ public void send(Exception exception, Guild guild, Channel channel, User user, discord4j.core.object.entity.Message message){ try { Sentry.getContext().clearTags(); if (guild != null) Sentry.getContext().addTag(GUILD, guild.getId().asString() + " - " + guild.getName()); if (channel != null) Sentry.getContext().addTag(CHANNEL, channel.getId().asString() + " - " + channel.getId()); if (user != null) Sentry.getContext().addTag(USER, user.getId().asString() + " - " + user.getUsername()); if (message != null) Sentry.getContext().addTag(MESSAGE, message.getContent().orElse("")); Sentry.capture(exception); } catch(Exception e){ Sentry.capture(exception); LOG.error("report", exception); Sentry.capture(e); LOG.error("report", e); } }
Example 2
Source File: DogCommand.java From SkyBot with GNU Affero General Public License v3.0 | 6 votes |
@Override public void execute(@Nonnull CommandContext ctx) { final String base = "https://random.dog/"; final GuildMessageReceivedEvent event = ctx.getEvent(); try { WebUtils.ins.getText(base + "woof").async((it) -> { final String finalS = base + it; if (finalS.contains(".mp4")) { sendEmbed(event, EmbedUtils.embedField("A video", "[Click for video](" + finalS + ")")); } else { sendEmbed(event, EmbedUtils.embedImage(finalS)); } }); } catch (Exception e) { //e.printStackTrace(); sendEmbed(event, EmbedUtils.embedMessage("**[OOPS]** Something broke, blame duncte \n(" + e.toString() + ")")); Sentry.capture(e); } }
Example 3
Source File: YoutubeApiPlaylistLoader.java From SkyBot with GNU Affero General Public License v3.0 | 6 votes |
@Override public AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId, Function<AudioTrackInfo, AudioTrack> trackFactory) { try { final YoutubePlaylistMetadata firstPage = getPlaylistPageById(playlistId, this.apiKey, null, true); if (firstPage == null) { throw new FriendlyException("This playlist does not exist", COMMON, null); } return buildPlaylist(firstPage, playlistId, selectedVideoId, trackFactory); } catch (IOException e) { Sentry.capture(e); throw ExceptionTools.wrapUnfriendlyExceptions(e); } }
Example 4
Source File: PerspectiveApi.java From SkyBot with GNU Affero General Public License v3.0 | 5 votes |
public static float checkSwearFilter(String text, String channelId, String apiKey, ProfanityFilterType filterType, ObjectMapper mapper) { if (text.isEmpty()) { return 0f; } try { final JsonNode json = makeRequest(text, channelId, apiKey, filterType, mapper); if (json.has("error")) { final String error = json.get("error").get("message").asText(); if ("Unable to detect language.".equals(error)) { return 0f; } throw new HttpException("Error while handling perspective api request: " + json); } final JsonNode score = json.get("attributeScores") .get(filterType.getType()) .get("summaryScore"); return Float.parseFloat(score.get("value").asText()); } catch (Exception e) { Sentry.capture(e); e.printStackTrace(); return 0f; } }
Example 5
Source File: SentryHelper.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void captureMessageErrorContext(String message, Class<?> clazz, String user) { final Context context = Sentry.getContext(); context.setUser(new UserBuilder().setUsername(user).build()); EventBuilder eventBuilder = new EventBuilder() .withMessage(message) .withLevel(Event.Level.ERROR) .withLogger(clazz.getName()); Sentry.capture(eventBuilder); Sentry.clearContext(); }
Example 6
Source File: SentryHelper.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void captureMessageContext(String message, Class<?> clazz, String user) { final Context context = Sentry.getContext(); context.setUser(new UserBuilder().setUsername(user).build()); EventBuilder eventBuilder = new EventBuilder() .withMessage(message) .withLevel(Event.Level.INFO) .withLogger(clazz.getName()); Sentry.capture(eventBuilder); Sentry.clearContext(); }
Example 7
Source File: SentryHelper.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void captureExceptionContext(String message, Throwable t, Class<?> clazz, String user) { final Context context = Sentry.getContext(); context.setUser(new UserBuilder().setUsername(user).build()); EventBuilder eventBuilder = new EventBuilder() .withMessage(message) .withLevel(Event.Level.ERROR) .withLogger(clazz.getName()) .withSentryInterface(new ExceptionInterface(t)); Sentry.capture(eventBuilder); Sentry.clearContext(); }
Example 8
Source File: SentryHelper.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void captureMessage(String message, Class<?> clazz) { EventBuilder eventBuilder = new EventBuilder() .withMessage(message) .withLevel(Event.Level.INFO) .withLogger(clazz.getName()); Sentry.capture(eventBuilder); }
Example 9
Source File: SentryHelper.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void captureException(String message, Throwable t, Class<?> clazz) { EventBuilder eventBuilder = new EventBuilder() .withMessage(message) .withLevel(Event.Level.ERROR) .withLogger(clazz.getName()) .withSentryInterface(new ExceptionInterface(t)); Sentry.capture(eventBuilder); }
Example 10
Source File: TrackScheduler.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
private void onStop() { //stop the track. LavalinkPlayer lavalinkPlayer = getAudioPlayer().getPlayer(); if (lavalinkPlayer.getPlayingTrack() != null) lavalinkPlayer.stopTrack(); getVoteStop().clear(); getVoteSkips().clear(); Guild g = getGuild(); if (g == null) { //Why? this.getAudioPlayer().destroy(); return; } boolean premium = MantaroData.db().getGuild(g).isPremium(); try { TextChannel ch = getRequestedTextChannel(); if (ch != null && ch.canTalk()) { ch.sendMessageFormat( language.get("commands.music_general.queue_finished"), EmoteReference.MEGA, premium ? "" : String.format(language.get("commands.music_general.premium_beg"), EmoteReference.HEART) ).queue(message -> message.delete().queueAfter(30, TimeUnit.SECONDS)); } } catch (Exception e) { Sentry.capture(e); } requestedChannel = 0; errorCount = 0; //If not set to null, those two objects will always be in scope and dangle around in the heap forever. //Some AudioTrack objects were of almost 500kb of size, I guess 100k of those can cause a meme. currentTrack = null; previousTrack = null; //Disconnect this audio player. this.getAudioPlayer().disconnect(); }
Example 11
Source File: TkAppFallback.java From jare with MIT License | 5 votes |
/** * Authenticated. * @param take Takes * @return Authenticated takes */ private static Take make(final Take take) { return new TkFallback( take, new FbChain( new FbStatus( HttpURLConnection.HTTP_NOT_FOUND, new RsWithStatus( new RsText("Page not found"), HttpURLConnection.HTTP_NOT_FOUND ) ), new FbStatus( HttpURLConnection.HTTP_BAD_REQUEST, new RsWithStatus( new RsText("Bad request"), HttpURLConnection.HTTP_BAD_REQUEST ) ), req -> { Sentry.capture(req.throwable()); return new Opt.Empty<>(); }, req -> new Opt.Single<>(TkAppFallback.fatal(req)) ) ); }
Example 12
Source File: EventManager.java From SkyBot with GNU Affero General Public License v3.0 | 5 votes |
@Override public void handle(@Nonnull GenericEvent event) { final JDA.ShardInfo shardInfo = event.getJDA().getShardInfo(); if (shouldFakeBlock) { //noinspection ConstantConditions if (shardInfo == null) { logger.warn(TextColor.RED + "Shard booting up (Event {})." + TextColor.RESET, event.getClass().getSimpleName()); return; } if (restartingShard == -1 || restartingShard == shardInfo.getShardId()) { return; } } for (final EventListener listener : this.listeners) { try { listener.onEvent(event); } catch (Throwable thr) { Sentry.capture(thr); logger.error("Error while handling event {}({}); {}", event.getClass().getName(), listener.getClass().getSimpleName(), thr.getLocalizedMessage()); logger.error("", thr); } } }
Example 13
Source File: CommandManager.java From SkyBot with GNU Affero General Public License v3.0 | 5 votes |
private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) { final CustomCommand cc = (CustomCommand) cmd; if (cc.getGuildId() != event.getGuild().getIdLong()) { return; } try { MDC.put("command.custom.message", cc.getMessage()); final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables)); final String message = parser.parse(cc.getMessage()); final MessageBuilder messageBuilder = new MessageBuilder(); final DataObject object = parser.get("embed"); if (!message.isEmpty()) { messageBuilder.setContent("\u200B" + message); } if (object != null) { final JDAImpl jda = (JDAImpl) event.getJDA(); final MessageEmbed embed = jda.getEntityBuilder().createMessageEmbed(object); messageBuilder.setEmbed(embed); } if (!messageBuilder.isEmpty()) { sendMsg(event, messageBuilder.build()); } parser.clear(); } catch (Exception e) { sendMsg(event, "Error with parsing custom command: " + e.getMessage()); Sentry.capture(e); } }
Example 14
Source File: ServerLogger.java From weMessage with GNU Affero General Public License v3.0 | 5 votes |
private static void logToSentry(Level level, String tag, String message, Exception ex){ if (!isSentryInitialized) return; Long previousTime = lastSentryExecution; long currentTimestamp = System.currentTimeMillis(); lastSentryExecution = currentTimestamp; if (previousTime == null || (currentTimestamp - previousTime > MINIMUM_INTERVAL)){ EventBuilder eventBuilder = new EventBuilder(); if (level != null){ eventBuilder.withLevel(level.sentryLevel()); } if (!StringUtils.isEmpty(tag)){ eventBuilder.withLogger(tag); } if (!StringUtils.isEmpty(message)){ eventBuilder.withMessage(message); } if (ex != null) { eventBuilder.withSentryInterface(new ExceptionInterface(ex)); } Sentry.capture(eventBuilder); } }
Example 15
Source File: TkApp.java From jpeek with MIT License | 4 votes |
/** * Ctor. * @param home Home directory * @return The take * @throws IOException If fails */ private static Take make(final Path home) throws IOException { final Futures futures = new Futures( new Reports(home) ); final BiFunc<String, String, Func<String, Response>> reports = new AsyncReports( // @checkstyle MagicNumber (1 line) new StickyFutures(futures, 100) ); return new TkSslOnly( new TkFallback( new TkForward( new TkFork( new FkRegex("/", new TkIndex()), new FkRegex("/robots.txt", new TkText("")), new FkRegex("/mistakes", new TkMistakes()), new FkRegex( "/flush", (Take) req -> new RsText( String.format("%d flushed", new Results().flush()) ) ), new FkRegex( "/upload", (Take) req -> new RsPage(req, "upload") ), new FkRegex("/do-upload", new TkUpload(reports)), new FkRegex("/all", new TkAll()), new FkRegex("/queue", new TkQueue(futures)), new FkRegex( ".+\\.xsl", new TkWithType( new TkClasspath(), "text/xsl" ) ), new FkRegex( "/jpeek\\.css", new TkWithType( new TkText( new TextOf( new ResourceOf("org/jpeek/jpeek.css") ).asString() ), "text/css" ) ), new FkRegex( "/([^/]+)/([^/]+)(.*)", new TkReport(reports, new Results()) ) ) ), new FbChain( new FbStatus( HttpURLConnection.HTTP_NOT_FOUND, (Fallback) req -> new Opt.Single<>( new RsWithStatus( new RsText(req.throwable().getMessage()), req.code() ) ) ), req -> { Sentry.capture(req.throwable()); return new Opt.Single<>( new RsWithStatus( new RsText( new TextOf(req.throwable()).asString() ), HttpURLConnection.HTTP_INTERNAL_ERROR ) ); } ) ) ); }
Example 16
Source File: StdErrorReporter.java From linstor-server with GNU General Public License v3.0 | 4 votes |
private String reportErrorImpl( Level logLevel, Throwable errorInfo, AccessContext accCtx, Peer client, String contextInfo ) { PrintStream output = null; long reportNr = errorNr.getAndIncrement(); final String logName = getLogName(reportNr); final Date errorTime = new Date(); try { output = openReportFile(logName); writeErrorReport(output, reportNr, client, errorInfo, errorTime, contextInfo); // write to h2 error database { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final String utf8 = StandardCharsets.UTF_8.name(); try (PrintStream ps = new PrintStream(baos, true, utf8)) { writeErrorReport(ps, reportNr, client, errorInfo, errorTime, contextInfo); } catch (UnsupportedEncodingException e) { logError(e.getMessage()); } h2ErrorReporter.writeErrorReportToDB( reportNr, client, errorInfo, instanceEpoch, errorTime, nodeName, dmModule, baos.toByteArray()); } final String logMsg = formatLogMsg(reportNr, errorInfo); switch (logLevel) { case ERROR: logError("%s", logMsg); break; case WARN: logWarning("%s", logMsg); break; case INFO: logInfo("%s", logMsg); break; case DEBUG: logDebug("%s", logMsg); break; case TRACE: logTrace("%s", logMsg); break; default: logError("%s", logMsg); reportError( new IllegalArgumentException( String.format( "Missing case label for enumeration value '%s'", logLevel.name() ) ) ); break; } Sentry.capture(errorInfo); } finally { closeReportFile(output); } return logName; }
Example 17
Source File: SentryLogger.java From OpenAs2App with BSD 2-Clause "Simplified" License | 4 votes |
protected void doLog(Throwable t, boolean terminated) { Sentry.capture(t); }
Example 18
Source File: AirUtils.java From SkyBot with GNU Affero General Public License v3.0 | 4 votes |
public static void handleExpiredReminders(List<Reminder> reminders, DatabaseAdapter adapter, PrettyTime prettyTime) { // Get the shardManager and a list of ints to purge the ids for final ShardManager shardManager = SkyBot.getInstance().getShardManager(); final List<Integer> toPurge = new ArrayList<>(); for (final Reminder reminder : reminders) { // The reminder message template final String message = String.format( "%s you asked me to remind you about \"%s\"", prettyTime.format(Date.from(reminder.getCreate_date())), reminder.getReminder().trim() ); final long channelId = reminder.getChannel_id(); // If we have a channel send the message to that if (channelId > 0) { final TextChannel channel = shardManager.getTextChannelById(channelId); // If we don't have a channel we can't send it there // TODO: DM the user instead? if (channel != null) { // Add the reminder to the list of the reminders to purge toPurge.add(reminder.getId()); sendMsgFormat(channel, "<@%s>, %s", reminder.getUser_id(), message); } // go to the next one and don't run the user code continue; } try { Objects.requireNonNull(shardManager.getShardById(0)) .openPrivateChannelById(reminder.getUser_id()) .flatMap( (c) -> c.sendMessage(message) ) .complete(); toPurge.add(reminder.getId()); } catch (NullPointerException ignored) { // this should never happen, shard 0 is always there } catch (ErrorResponseException errorResponseEx) { final ErrorResponse errorResponse = errorResponseEx.getErrorResponse(); if ( // The account probably got deleted or something errorResponse == ErrorResponse.UNKNOWN_USER || // we cannot dm this user (has dms blocked?) errorResponse == ErrorResponse.CANNOT_SEND_TO_USER ) { toPurge.add(reminder.getId()); } } catch (Exception e) { Sentry.capture(e); } } // get a date that is 2 days in the future final Instant plusTwoDays = Instant.now().plus(2L, ChronoUnit.DAYS); // Remove any reminders that have not been removed after 2 days final List<Integer> extraRemoval = reminders.stream() .filter((reminder) -> reminder.getReminder_date().isAfter(plusTwoDays)) .map(Reminder::getId) .collect(Collectors.toList()); toPurge.addAll(extraRemoval); adapter.purgeReminders(toPurge); }
Example 19
Source File: CommandManager.java From SkyBot with GNU Affero General Public License v3.0 | 4 votes |
private Triple<Boolean, Boolean, Boolean> addCustomCommand(CustomCommand command, boolean insertInDb, boolean isEdit) { if (command.getName().contains(" ")) { throw new IllegalArgumentException("Name can't have spaces!"); } final boolean commandFound = this.customCommands.stream() .anyMatch((cmd) -> cmd.getName().equalsIgnoreCase(command.getName()) && cmd.getGuildId() == command.getGuildId()) && !isEdit; final boolean limitReached = this.customCommands.stream().filter((cmd) -> cmd.getGuildId() == command.getGuildId()).count() >= 50 && !isEdit; if (commandFound || limitReached) { return new Triple<>(false, commandFound, limitReached); } if (insertInDb) { try { final CompletableFuture<Triple<Boolean, Boolean, Boolean>> future = new CompletableFuture<>(); if (isEdit) { this.variables.getDatabaseAdapter() .updateCustomCommand(command.getGuildId(), command.getName(), command.getMessage(), command.isAutoResponse(), (triple) -> { future.complete(triple); return null; }); } else { this.variables.getDatabaseAdapter() .createCustomCommand(command.getGuildId(), command.getName(), command.getMessage(), (triple) -> { future.complete(triple); return null; }); } final Triple<Boolean, Boolean, Boolean> res = future.get(); if (res != null && !res.getFirst()) { return res; } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); Sentry.capture(e); } } if (isEdit) { this.customCommands.remove(getCustomCommand(command.getName(), command.getGuildId())); } this.customCommands.add(command); return new Triple<>(true, false, false); }