Sobes.tech
Junior

If you cannot throw an Error but want to wrap an exception, what should you use?

sobes.tech AI

Answer from AI

If in your code you cannot throw exceptions, but need to handle errors and pass exception information further, you can use a pattern of wrapping the error in an object or structure with fields for error code and message.

For example, create a class or structure Result that contains:

  • a success flag (bool IsSuccess)
  • an error message (string ErrorMessage)
  • additional data (if needed)

Instead of throwing an exception, the method returns such an object, and the calling code checks the result:

public class Result {
    public bool IsSuccess { get; set; }
    public string ErrorMessage { get; set; }
}

public Result DoWork() {
    try {
        // code
        return new Result { IsSuccess = true };
    } catch (Exception ex) {
        // wrap the exception in Result
        return new Result { IsSuccess = false, ErrorMessage = ex.Message };
    }
}

Thus, the exception is not thrown but passed as part of the result.

If you cannot throw an Error but want to wrap an… - sobes.tech