def handler500(request, *args, **argv): print("yoyo") print(last_event_id()) return render(request, "500.html", { 'sentry_event_id': last_event_id(), }, status=500)
def test_500(client): old_event_id = last_event_id() content, status, headers = client.get("/view-exc") assert status.lower() == "500 internal server error" content = b"".join(content).decode("utf-8") event_id = last_event_id() assert content == "Sentry error: %s" % event_id assert event_id is not None assert old_event_id != event_id
def test_500(sentry_init, client): sentry_init(integrations=[DjangoIntegration()], send_default_pii=True) old_event_id = last_event_id() content, status, headers = client.get("/view-exc") assert status.lower() == "500 internal server error" content = b"".join(content).decode("utf-8") event_id = last_event_id() assert content == "Sentry error: %s" % event_id assert event_id is not None assert old_event_id != event_id
def server_error(request, template_name='500.html'): """ 500 error handler. """ urlname = resolve(request.path).url_name submission_urls = [ 'receiver_secure_post', 'receiver_secure_post_with_app_id', 'receiver_post_with_app_id' ] if urlname in submission_urls + ['app_aware_restore']: return HttpResponse(status=500) domain = get_domain_from_url(request.path) or '' # hat tip: http://www.arthurkoziel.com/2009/01/15/passing-mediaurl-djangos-500-error-view/ t = loader.get_template(template_name) type, exc, tb = sys.exc_info() traceback_text = format_traceback_the_way_python_does(type, exc, tb) traceback_key = uuid.uuid4().hex cache.cache.set(traceback_key, traceback_text, 60*60) return HttpResponseServerError(t.render( context={ 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': settings.STATIC_URL, 'domain': domain, '500traceback': traceback_key, 'sentry_event_id': last_event_id(), }, request=request, ))
def captureException(self, exception, value, tb): from .local_server import LocalServer from .local_config import LocalConfig local_server = LocalServer.instance().localServerSettings() if local_server["report_errors"]: if not SENTRY_SDK_AVAILABLE: return if os.path.exists(LocalConfig.instance().runAsRootPath()): log.warning( "User is running application as root. Crash reports disabled." ) sys.exit(1) return if os.path.exists(".git"): log.warning( "A .git directory exists, crash reporting is turned off for developers." ) sys.exit(1) return try: sentry_sdk.capture_exception((exception, value, tb)) log.info("Crash report sent with event ID: {}".format( sentry_sdk.last_event_id())) except Exception as e: log.error("Can't send crash report to Sentry: {}".format(e))
def _(app, request, e): if isinstance(e, TrytondBaseException): return else: event_id = last_event_id() data = TrytondUserError(str(event_id), str(e)) return app.make_response(request, data)
def server_error(request, *args, **argv): return render(request, "500.html", { 'sentry_event_id': last_event_id(), 'sentry_dsn': getattr(settings, 'SENTRY_DSN', '') }, status=500)
def test_simple(post_event_with_sdk): event = post_event_with_sdk("internal client test") assert event assert event.data["project"] == settings.SENTRY_PROJECT assert event.data["event_id"] == last_event_id() assert event.data["logentry"]["formatted"] == "internal client test"
def route_errors(error, user_dict=None): data = dict() # Handle the case where the header isn't present if user_dict['username'] is not None: data['username'] = user_dict['account'].uid data['name'] = user_dict['account'].cn else: data['username'] = "******" data['name'] = "Unknown" # Figure out what kind of error was passed if isinstance(error, int): code = error elif hasattr(error, 'code'): code = error.code else: # Unhandled exception code = 500 # Is this a 404? if code == 404: error_desc = "Page Not Found" else: error_desc = type(error).__name__ return render_template('errors.html', error=error_desc, error_code=code, event_id=sentry_sdk.last_event_id(), **data), int(code)
def wrapper(*args, **kwargs): flow_id = data = None try: if isinstance(args[0], (str, bytes)): try: data = json.loads(args[0]) except json.JSONDecodeError: pass elif isinstance(args[0], dict): data = args[0] if data: flow_id = data.get('metadata', {}).get('flow_id') except IndexError: pass transaction = Transaction.continue_from_headers( {'sentry-trace': flow_id}, op='message_handler', name=transaction_name or f'{func.__module__}.{func.__name__}', ) with Hub.current.start_transaction(transaction): result = func(*args, **kwargs) _logger.debug( "Logged message handling with trace_id=%s, span_id=%s, id=%s", transaction.trace_id, transaction.span_id, last_event_id()) return result
def handler500(request): """500 error handler which includes ``request`` in the context. Templates: `500.html` Context: None """ use_sentry = False sentry_dsn = None event_id = None try: import sentry_sdk if sentry_sdk.Hub.current.client: use_sentry = True sentry_dsn = sentry_sdk.Hub.current.client.dsn event_id = sentry_sdk.last_event_id() except ImportError: pass return render(request, '500.html', status=500, context={ 'use_sentry': use_sentry, 'sentry_dsn': sentry_dsn, 'event_id': event_id, })
def captureException(self, exception, value, tb): from .local_server import LocalServer from .local_config import LocalConfig local_server = LocalServer.instance().localServerSettings() if local_server["report_errors"]: if not SENTRY_SDK_AVAILABLE: log.warning( "Cannot capture exception: Sentry SDK is not available") return if os.path.exists(LocalConfig.instance().runAsRootPath()): log.warning( "User is running application as root. Crash reports disabled." ) return if not hasattr(sys, "frozen") and os.path.exists( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".git")): log.warning( ".git directory detected, crash reporting is turned off for developers." ) return try: error = (exception, value, tb) sentry_sdk.capture_exception(error=error) log.info("Crash report sent with event ID: {}".format( sentry_sdk.last_event_id())) except Exception as e: log.warning("Can't send crash report to Sentry: {}".format(e))
def handler500(request, *args, **argv): return render( request, "500.html", {"sentry_event_id": last_event_id()}, status=500, )
async def on_command_error(self, ctx: ContextPlus, error: commands.CommandError): await self.register_command(ctx) if not isinstance( error, (commands.CommandInvokeError, commands.ConversionError)): return error = error.original if isinstance(error, (discord.Forbidden, discord.NotFound)): return self.bot.console.log( "Command Error, check sentry or discord error channel") e = discord.Embed(title="Command Error", colour=0xCC3366) e.add_field(name="Name", value=ctx.command.qualified_name) e.add_field(name="Author", value=f"{ctx.author} (ID: {ctx.author.id})") fmt = f"Channel: {ctx.channel} (ID: {ctx.channel.id})" if ctx.guild: fmt = f"{fmt}\nGuild: {ctx.guild} (ID: {ctx.guild.id})" e.add_field(name="Location", value=fmt, inline=False) e.add_field( name="Content", value=textwrap.shorten(ctx.message.content, width=512), ) e.add_field( name="Bot Instance", value=self.bot.instance_name, ) exc = "".join( traceback.format_exception(type(error), error, error.__traceback__, chain=False)) e.description = f"```py\n{textwrap.shorten(exc, width=2035)}\n```" e.timestamp = datetime.datetime.utcnow() await self.webhook("errors").send(embed=e) log.error(exc) e.description = _( "```An error occurred, the bot owner has been advertised...```", ctx, self.bot.config, ) e.remove_field(0) e.remove_field(1) e.remove_field(1) if self.bot.instance_name != "dev": sentry_sdk.capture_exception(error) e.set_footer(text=sentry_sdk.last_event_id()) await ctx.send(embed=e)
def error_500_view(request, *args, **argv): return render( request, "500.html", { "sentry_event_id": last_event_id(), }, status=500, )
def handler_500(request, *args, **kwargs): if settings.SENTRY_ENABLED: from sentry_sdk import last_event_id context = {'sentry_event_id': last_event_id()} else: context = {} return render(request, '500.html', context=context, status=500)
def handler500(request, *args, **argv): from sentry_sdk import last_event_id return render( request, "500.html", {"sentry_event_id": last_event_id(), "sentry_dsn": settings.SENTRY_DSN_API}, status=500, )
def dispatch(self, *args, **kwargs): """Little wrapper so django accepts this function""" type_, _error, trace = sys.exc_info() self.extra_context = { 'exception': str(type_), 'error': traceback.format_tb(trace), 'hide_navbar': True, 'sentry_event_id': last_event_id() } return super().dispatch(*args, **kwargs)
def server_error(request, *args, **argv): return render( request, "500.html", { "sentry_event_id": last_event_id(), "sentry_dsn": getattr(settings, "SENTRY_DSN", ""), }, status=500, )
def handler500(request, *args, **argv): return render( request, "500.html", { "sentry_event_id": last_event_id(), "sentry_dsn": OW4_SENTRY_DSN }, status=500, )
def handler500(request, *args, **argv): return render( request, 'app/root/500.html', { 'sentry_dsn': settings.SENTRY_DSN, 'sentry_event_id': last_event_id(), }, status=500, )
def handler500(request, *args, **argv): email = None name = None if request.user: email = request.user.email name = f"{request.user.first_name} {request.user.last_name}" return render(request, "500.html", { 'sentry_event_id': last_event_id(), "email": email, "name": name }, status=500)
def server_error(request): try: template = loader.get_template('500.html') except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return HttpResponseServerError( template.render({ 'request': request, 'sentry_event_id': last_event_id(), }))
def test_recursion_breaker(post_event_with_sdk): # If this test terminates at all then we avoided recursion. with mock.patch("sentry.event_manager.EventManager.save", side_effect=ValueError("oh no!")) as save: with pytest.raises(ValueError): post_event_with_sdk("internal client test") assert_mock_called_once_with_partial(save, settings.SENTRY_PROJECT, cache_key=u"e:{}:1".format( last_event_id()))
def server_error(request): try: template = loader.get_template('500.html') except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') r = HttpResponseServerError(template.render({ 'request': request, 'sentry_event_id': last_event_id(), })) r.xframe_options_exempt = True return r
def process_exception(self, request, exception): logger.exception(traceback.format_exc(limit=3)) if settings.DEBUG: raise exception return render(request, "500.html", { 'sentry_event_id': last_event_id(), 'SENTRY_DSN': settings.SENTRY_DSN, }, status=500)
def trigger(self, exception, spider=None, extra=None): extradata = {} if extra is not None: extradata.update(extra) extradata['spider'] = spider.name if spider else "" with sentry_sdk.push_scope() as scope: for k, v in extradata.iteritems(): scope.set_extra(k, v) sentry_sdk.capture_exception(sys.exc_info()) ident = sentry_sdk.last_event_id() logging.log(logging.INFO, "Sentry Exception ID '%s'" % ident) return None
def custom_500_view(request): admin_settings = SiteAdminSettings.load() ret_data = { "generic_title": admin_settings.err_500_title, "generic_content": admin_settings.err_500_content } if admin_settings.err_500_sentry: ret_data['sentry_event_id'] = last_event_id() ret_data['sentry_dsn'] = os.environ.get('SENTRY_DSN') return render(request, "errors/500.html", ret_data, status=500)
async def respond_details(request: Request, content: Any, status_code: int = 500, headers: dict = None): response = { 'detail': jsonable_encoder(content), } event_id = sentry_sdk.last_event_id() or request.scope.get('sentry_event_id') if event_id: response['event_id'] = event_id return JSONResponse( content=response, status_code=status_code, headers=headers, )
def signal_receiver(self, signal=None, sender=None, *args, **kwargs): message = signal extra = { 'sender': sender, 'signal': signal, 'args': args, 'kwargs': kwargs, } with sentry_sdk.push_scope() as scope: for k, v in extra.iteritems(): scope.set_extra(k, v) sentry_sdk.capture_message(message) ident = sentry_sdk.last_event_id() return ident
def capture_exception(self): if not SENTRY_SDK_AVAILABLE: return if os.path.exists(".git"): log.warning(".git directory detected, crash reporting is turned off for developers.") return server_config = Config.instance().get_section_config("Server") if server_config.getboolean("report_errors"): try: sentry_sdk.capture_exception() log.info("Crash report sent with event ID: {}".format(sentry_sdk.last_event_id())) except Exception as e: log.error("Can't send crash report to Sentry: {}".format(e))