Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate exception from one type to another

If have some framework that expects callbacks of a type like

void fcn(F& data);

It can handle exceptions of type ExF.

In my callback, I am using some third party library that throws exceptions of type ExL. So my callbacks look like

void fcn1(F& data)
{
  try
  {
     // call library
  }
  catch(const ExL& ex)
  {
     ExF exf = make_ExF(ex);
     throw exf;
  }
}

Now I want to write more callbacks fcn2, fcn3, ... that use the library but do not want to repeat the same try/catch all the time. In particular, maybe I will add another

catch(const ExL2& ex)

block in the future for several callbacks. I cannot change the code (in particular the exception types) in the framework and the library. How can I avoid repeating the try/catch blocks?

like image 654
Helmut Zeisel Avatar asked Nov 27 '18 09:11

Helmut Zeisel


1 Answers

Take advantage of the fact that while you are in a catch block, you have a "currently handled exception" that you can just throw; again. This allows you to move the logic into another function

void except_translate() {
  try
  {
     throw;
  }
  catch(const ExL& ex)
  {
     ExF exf = make_ExF(ex);
     throw exf;
  }
}

void fcn1(F& data)
{
  try
  {
     // call library
  }
  catch(...)
  {
     except_translate();
  }
}

This technique is known (for googling purposes) as a Lippincott function. It centralizes the error translation logic into one place, so you can easily extend that one function with another handler and it will translate it for all functions that use this utility.

like image 60
StoryTeller - Unslander Monica Avatar answered Oct 15 '22 13:10

StoryTeller - Unslander Monica