Skip to content

Commit

Permalink
Handle no run when rescuing errors in TaskJob (#375)
Browse files Browse the repository at this point in the history
* Handle no run when rescuing errors in TaskJob
  • Loading branch information
adrianna-chang-shopify authored Mar 18, 2021
1 parent 1f9922a commit 9dfd0fc
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 7 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,15 @@ end

The error handler should be a lambda that accepts three arguments:

* `error`: The object containing the exception that was raised.
* `error`: The exception that was raised.
* `task_context`: A hash with additional information about the Task and the
error:
* `task_name`: The name of the Task that errored
* `started_at`: The time the Task started
* `ended_at`: The time the Task errored
Note that `task_context` may be empty if the Task produced an error before any
context could be gathered (for example, if deserializing the job to process
your Task failed).
* `errored_element`: The element, if any, that was being processed when the
Task raised an exception. If you would like to pass this object to your
exception monitoring service, make sure you **sanitize the object** to avoid
Expand Down
17 changes: 11 additions & 6 deletions app/jobs/maintenance_tasks/task_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,18 @@ def after_perform

def on_error(error)
@ticker.persist if defined?(@ticker)
@run.persist_error(error)

task_context = {
task_name: @run.task_name,
started_at: @run.started_at,
ended_at: @run.ended_at,
}
if defined?(@run)
@run.persist_error(error)

task_context = {
task_name: @run.task_name,
started_at: @run.started_at,
ended_at: @run.ended_at,
}
else
task_context = {}
end
errored_element = @errored_element if defined?(@errored_element)
MaintenanceTasks.error_handler.call(error, task_context, errored_element)
end
Expand Down
21 changes: 21 additions & 0 deletions test/jobs/maintenance_tasks/task_job_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -316,5 +316,26 @@ class << self
ensure
MaintenanceTasks.error_handler = error_handler_before
end

test '.perform_now handles case where run is not set and calls error handler' do
error_handler_before = MaintenanceTasks.error_handler
handled_error = nil
handled_task_context = nil
MaintenanceTasks.error_handler = ->(error, task_context, _errored_el) do
handled_error = error
handled_task_context = task_context
end

RaisingTaskJob = Class.new(TaskJob) do
before_perform(prepend: true) { raise 'Uh oh!' }
end

RaisingTaskJob.perform_now(@run)

assert_equal('Uh oh!', handled_error.message)
assert_empty(handled_task_context)
ensure
MaintenanceTasks.error_handler = error_handler_before
end
end
end

0 comments on commit 9dfd0fc

Please sign in to comment.