Skip to content

Proposal: An Error class which has an inner error. #533

Open
@opcodewriter

Description

@opcodewriter

With the result pattern, I often feel the need to have code which is able to create an error based on another error:

public UnitResult<Error> SaveItem(Item item)
{  
     Result<Stream, Error> getFileResult  = OpenFile(...);
     if(getFileResult.IsFailure)
     {
           var error = .... ; // Create a new error based on an the getFileResult.Error
          
           return UniResult.Failed(error2);
    }

     ...
}

In order for Error class to be able to support inner errors, I created it like this;

    public class Error(string message, Exception? exception, Error? innerError)
    {
        public string Message { get; } = message;
        public Exception? Exception { get; } = exception;
        public Error? InnerError { get; } = innerError;

        public Error(string message) : this(message, exception: null, innerError: null) { }
        public Error(string message, Exception exception) : this(message, exception, innerError: null) { }
        public Error(string message, Error innerError) : this(message, exception: null, innerError) { }

        public static implicit operator Error(string message) => new(message);
    }

which allows me to write:

 return UnitResult.Failed(error: new("Add item failed.", getFileResult.Error));

But since this Error class does not already exist in CSharpFunctionalExtensions, am I the first who needs this concept of inner errors?

I think it's important to keep a stack of inner errors, similar to how exceptions work.

Looking forward to hear your thoughts!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions