Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Sentry.with_exception_captured helper #1814

Merged
merged 3 commits into from
May 20, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
## Unreleased

## Features

- Add `Sentry.with_exception_captured` helper [#1814](https://github.com/getsentry/sentry-ruby/pull/1814)

Usage:

```rb
Sentry.with_exception_captured do
1/1 #=> 1 will be returned
end

Sentry.with_exception_captured do
1/0 #=> ZeroDivisionError will be reported and re-raised
end
```

### Bug Fixes

- Don't require a DB connection, but release one if it is acquired [#1812](https://github.com/getsentry/sentry-ruby/pull/1812)
Expand Down
19 changes: 19 additions & 0 deletions sentry-ruby/lib/sentry-ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,25 @@ def capture_exception(exception, **options, &block)
get_current_hub.capture_exception(exception, **options, &block)
end

# Takes a block and evaluates it. If the block raised an exception, it reports the exception to Sentry and re-raises it.
# If the block ran without exception, it returns the evaluation result.
#
# @example
# Sentry.with_exception_captured do
# 1/1 #=> 1 will be returned
# end
#
# Sentry.with_exception_captured do
# 1/0 #=> ZeroDivisionError will be reported and re-raised
# end
#
def with_exception_captured(**options, &block)
yield
rescue Exception => e
capture_exception(e, **options)
raise
end

# Takes a message string and reports it to Sentry via the currently active hub.
#
# @yieldparam scope [Scope]
Expand Down
18 changes: 18 additions & 0 deletions sentry-ruby/spec/sentry_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,24 @@
end
end

describe ".with_exception_captured" do
it "returns the block's result" do
result = described_class.with_exception_captured { 2 }

expect(result).to eq(2)
expect(transport.events.count).to eq(0)
end

it "rescues and reports the exception happened inside the block" do
expect do
described_class.with_exception_captured(tags: { foo: "bar" }) { 1/0 }
end.to raise_error(ZeroDivisionError)

expect(transport.events.count).to eq(1)
expect(transport.events.first.tags).to eq(foo: "bar")
end
end

describe ".capture_message" do
let(:message) { "Test" }

Expand Down