bzablocki commented on code in PR #31856:
URL: https://github.com/apache/beam/pull/31856#discussion_r1717079723


##########
sdks/python/apache_beam/transforms/error_handling_test.py:
##########
@@ -0,0 +1,122 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import logging
+import unittest
+
+import apache_beam as beam
+from apache_beam.testing.util import assert_that
+from apache_beam.testing.util import equal_to
+from apache_beam.transforms import error_handling
+
+
+class PTransformWithErrors(beam.PTransform):
+  def __init__(self, limit):
+    self._limit = limit
+    self._error_handler = None
+
+  def with_error_handler(self, error_handler):
+    self._error_handler = error_handler
+    return self
+
+  def expand(self, pcoll):
+    limit = self._limit
+
+    def process(element):
+      if len(element) < limit:
+        return element.title()
+      else:
+        return beam.pvalue.TaggedOutput('bad', element)
+
+    def raise_on_everything(element):
+      raise ValueError(element)
+
+    good, bad = pcoll | beam.Map(process).with_outputs('bad', main='good')
+    if self._error_handler:
+      self._error_handler.add_error_pcollection(bad)
+    else:
+      # Will throw an exception if there are any bad elements.
+      _ = bad | beam.Map(raise_on_everything)
+    return good
+
+
+def exception_throwing_map(x, limit):
+  if len(x) > limit:
+    raise ValueError(x)
+  else:
+    return x.title()
+
+
+class ErrorHandlingTest(unittest.TestCase):
+  def test_error_handling(self):
+    with beam.Pipeline() as p:
+      pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+      with error_handling.ErrorHandler(
+          beam.Map(lambda x: "error: %s" % x)) as error_handler:
+        result = pcoll | PTransformWithErrors(3).with_error_handler(
+            error_handler)
+      error_pcoll = error_handler.output()
+
+      assert_that(result, equal_to(['A', 'Bb']), label='CheckGood')
+      assert_that(error_pcoll, equal_to(['error: cccc']), label='CheckBad')
+
+  def test_error_handling_pardo(self):
+    with beam.Pipeline() as p:
+      pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+      with error_handling.ErrorHandler(
+          beam.Map(lambda x: "error: %s" % x[0])) as error_handler:

Review Comment:
   Why do we access here the first element in the array (`Map(lambda x: "error: 
%s" % x[0]))`) and in the test above we just access the entire element 
(`Map(lambda x: "error: %s" % x)`)?



##########
sdks/python/apache_beam/transforms/core.py:
##########
@@ -1633,7 +1636,19 @@ def with_exception_handling(
         use_subprocess,
         threshold,
         threshold_windowing,
-        timeout)
+        timeout,
+        error_handler)
+
+  def with_error_handler(self, error_handler, **exception_handling_kwargs):

Review Comment:
   Could we also have a unit test that would show how the 
`**exception_handling_kwargs` can be used?



##########
sdks/python/apache_beam/transforms/error_handling_test.py:
##########
@@ -0,0 +1,122 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import logging
+import unittest
+
+import apache_beam as beam
+from apache_beam.testing.util import assert_that
+from apache_beam.testing.util import equal_to
+from apache_beam.transforms import error_handling
+
+
+class PTransformWithErrors(beam.PTransform):
+  def __init__(self, limit):
+    self._limit = limit
+    self._error_handler = None
+
+  def with_error_handler(self, error_handler):
+    self._error_handler = error_handler
+    return self
+
+  def expand(self, pcoll):
+    limit = self._limit
+
+    def process(element):
+      if len(element) < limit:
+        return element.title()
+      else:
+        return beam.pvalue.TaggedOutput('bad', element)
+
+    def raise_on_everything(element):
+      raise ValueError(element)
+
+    good, bad = pcoll | beam.Map(process).with_outputs('bad', main='good')
+    if self._error_handler:
+      self._error_handler.add_error_pcollection(bad)
+    else:
+      # Will throw an exception if there are any bad elements.
+      _ = bad | beam.Map(raise_on_everything)
+    return good
+
+
+def exception_throwing_map(x, limit):
+  if len(x) > limit:
+    raise ValueError(x)
+  else:
+    return x.title()
+
+
+class ErrorHandlingTest(unittest.TestCase):
+  def test_error_handling(self):
+    with beam.Pipeline() as p:
+      pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+      with error_handling.ErrorHandler(
+          beam.Map(lambda x: "error: %s" % x)) as error_handler:
+        result = pcoll | PTransformWithErrors(3).with_error_handler(
+            error_handler)
+      error_pcoll = error_handler.output()
+
+      assert_that(result, equal_to(['A', 'Bb']), label='CheckGood')
+      assert_that(error_pcoll, equal_to(['error: cccc']), label='CheckBad')
+
+  def test_error_handling_pardo(self):
+    with beam.Pipeline() as p:
+      pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+      with error_handling.ErrorHandler(
+          beam.Map(lambda x: "error: %s" % x[0])) as error_handler:
+        result = pcoll | beam.Map(
+            exception_throwing_map, limit=3).with_error_handler(error_handler)
+      error_pcoll = error_handler.output()
+
+      assert_that(result, equal_to(['A', 'Bb']), label='CheckGood')
+      assert_that(error_pcoll, equal_to(['error: cccc']), label='CheckBad')
+
+  def test_error_on_unclosed_error_handler(self):
+    with self.assertRaisesRegex(RuntimeError, r'.*Unclosed error handler.*'):
+      with beam.Pipeline() as p:
+        pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+        # Use this outside of a context to allow it to remain unclosed.
+        error_handler = error_handling.ErrorHandler(beam.Map(lambda x: x))
+        _ = pcoll | PTransformWithErrors(3).with_error_handler(error_handler)
+
+  def test_collecting_error_handler(self):
+    with beam.Pipeline() as p:
+      pcoll = p | beam.Create(['a', 'bb', 'cccc'])
+      with error_handling.CollectingErrorHandler() as error_handler:
+        result = pcoll | beam.Map(
+            exception_throwing_map, limit=3).with_error_handler(error_handler)
+      error_pcoll = error_handler.output() | beam.Map(lambda x: x[0])
+
+      assert_that(result, equal_to(['A', 'Bb']), label='CheckGood')
+      assert_that(error_pcoll, equal_to(['cccc']), label='CheckBad')
+
+  def test_error_on_collecting_error_handler_without_output_retrieval(self):

Review Comment:
   Shall we also add a unit test with the CollectingErrorHandler that is closed 
but not consumed?



##########
sdks/python/apache_beam/transforms/error_handling.py:
##########
@@ -0,0 +1,126 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Utilities for gracefully handling errors and excluding bad elements."""
+
+import traceback
+
+from apache_beam import transforms
+
+
+class ErrorHandler:
+  """ErrorHandlers are used to skip and otherwise process bad records.
+
+  Error handlers allow one to implement the "dead letter queue" pattern in
+  a fluent manner, disaggregating the error processing specification from
+  the main processing chain.
+
+  This is typically used as follows::
+
+    with error_handling.ErrorHandler(WriteToSomewhere(...)) as error_handler:
+      result = pcoll | SomeTransform().with_error_handler(error_handler)
+
+  in which case errors encountered by `SomeTransform()`` in processing pcoll
+  will be written by the PTransform `WriteToSomewhere(...)` and excluded from
+  `result` rather than failing the pipeline.
+
+  To implement `with_error_handling` on a PTransform, one caches the provided
+  error handler for use in `expand`.  During `expand()` one can invoke
+  `error_handler.add_error_pcollection(...)` any number of times with
+  PCollections containing error records to be processed by the given error
+  handler, or (if applicable) simply invoke `with_error_handling(...)` on any
+  subtransforms.
+
+  The `with_error_handling` should accept `None` to indicate that error 
handling
+  is not enabled (and make implementation-by-forwarding-error-handers easier).

Review Comment:
   Typo
   ```suggestion
     is not enabled (and make implementation-by-forwarding-error-handlers 
easier).
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to