Click here to Skip to main content
14,360,161 members

Error Handling in SOLID C# .NET – The Operation Result Approach

Rate this:
4.66 (47 votes)
Please Sign up or sign in to vote.
4.66 (47 votes)
26 Aug 2015CPOL
Error handling often brings down an otherwise good design, this article offers an approach to standardize and simplify your error handling particularly in SOLID applications.

Problem

Say we have our beautifully engineered, following SOLID principals, FileStorageService class which is an implementation of IStorageService:

public interface IStorageService
{
    void WriteAllBytes(string path, byte[] buffer);
    byte[] ReadAllBytes(string path);
}

public class FileStorageService : IStorageService
{
    public void WriteAllBytes(string path, byte[] buffer)

    {
        File.WriteAllBytes(path, buffer);
    }

    public byte[] ReadAllBytes(string path)
    {
        return File.ReadAllBytes(path);
    }
}

What if calling one of the methods resulted in an Exception? As we know reading and writing to files can result in a litany of Exceptions such as: IOException, DirectoryNotFoundException, FileNotFoundException, UnauthorizedAccessException… and of course the ever possible OutOfMemoryException (a real concern reading all bytes from a file).

Solution 1 – Not My Problem

We could not care about it, say it is the responsibility of the caller. Problem with that is since the caller is (should be) using an IStorageService how should it know what Exceptions the run time implementation could throw? Moreover the run time implementation could change in future and as a result the Exceptions it could throw. The lazy solution to this is just to wrap your call in catch-all exception handler:

IStorageService myStorageService = Resolver.Resolve<IStorageService>();
try
{
    myStorageService.ReadAllBytes("C:\stuff.data");
}

catch (Exception exception)
{
    // please don't write generic error messages like this, be specific
    Logger.Log("Oops something went wrong: " + exception.Message);
}

Hopefully we already know why catching Exception is bad. Also everyone using IStorageService has to wrap every call in their own Exception handling.

Solution 2 – Create new Exception Type

Perhaps an improvement upon the previous solution would be to create our own Exception Type, say: StorageReadException which we could throw in our implementation when only an Exception we expect and can deal with occurs. Then the caller can safely only handle StorageReadException regardless of the of the runtime implementation, e.g.:

public class StorageReadException : Exception
{
    public StorageReadException(Exception innerException)
        : base(innerException.Message, innerException)
    {
    }
}

And in our `FileStorageService` from earlier:

public byte[] ReadAllBytes(string path)
{
    try
    {
        return File.ReadAllBytes(path);
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        throw new StorageReadException(fileNotFoundException);
    }
}

And our caller could:

IStorageService myStorageService = Resolver.Resolve<IStorageService>();
try
{
    myStorageService.ReadAllBytes(path);
}
catch (StorageReadException sre)
{
    Logger.Log(String.Format("Failed to read file from path, {0}: {1}", path, sre.Message));
}

Issues I have with his approach are: we have to create a new Type consumers may be unfamiliar with and the caller still has to write a try catch block every call.

Solution 3 – Try Pattern with Complex Result

IStorageService operations can fail, i.e. it is not exceptional to fail, let’s alleviate our consumers having to write their own Exception handling every time by using the Try pattern – the same pattern on int (Int32) when parsing a string: bool TryParse(string s, out int result). We could change 

byte[] ReadAllBytes(string path)

to:

bool TryReadAllBytes(string path, out byte[] result)

But that does not give us much information such as why the operation failed; perhaps we want to show a message to the user giving them some information about the failure - and IStorageService cannot be expected to show a messages as thats not its responsibility. So instead of bool lets’ return a new Type containing: whether the operation was a success, the result of the operation if was successful otherwise a message why not and details about the Exception that caused the failure which the caller can choose to use, introducing OperationResult<TResult>:

public class OperationResult<TResult>
{
    private OperationResult ()
    {
    }

    public bool Success { get; private set; }
    public TResult Result { get; private set; }
    public string NonSuccessMessage { get; private set; }
    public Exception Exception { get; private set; }

    public static OperationResult<TResult> CreateSuccessResult(TResult result)
    {
        return new OperationResult<TResult> { Success = true, Result = result};
    }

    public static OperationResult<TResult> CreateFailure(string nonSuccessMessage)
    {
        return new OperationResult<TResult> { Success = false, NonSuccessMessage = nonSuccessMessage};
    }

    public static OperationResult<TResult> CreateFailure(Exception ex)
    {
        return new OperationResult<TResult>
        {
            Success = false,
            NonSuccessMessage = String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace),
            Exception = ex
        };
    }
}

(I used a private constructor so one of the Create() methods have to be used ensuring Result has to be set if successful; otherwise NonSuccessMessage has to be supplied if not). We can change FileStorageService’s ReadAllBytes() method (and the interface) to:

public OperationResult<byte[]> TryReadAllBytes(string path)
{
    try
    {
        var bytes = File.ReadAllBytes(path);
        return OperationResult<byte[]>.CreateSuccessResult(bytes);
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        return OperationResult<byte[]>.CreateFailure(fileNotFoundException);
    }
}

And the calling code becomes:

var result = myStorageService.TryReadAllBytes(path);
if(result.Success)
{
    // do something
}
else
{
    Logger.Log(String.Format("Failed to read file from path, {0}: {1}", path, result.NonSuccessMessage));
}

That’s it! Now if an Exception we cannot handle occurs it bubbles as it should; if an expected Exception occurred in the implementation we can use the information on the retuned OperationResult.

OperationResult<TResult> can be used across the API on all operations that can fail.

History

27 August 2015 - Inital Version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

markmnl
Zimbabwe Zimbabwe
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pin
zilongkk22-Jul-18 1:29
memberzilongkk22-Jul-18 1:29 
GeneralRe: My vote of 1 Pin
Maxx the Axe21-Aug-19 8:41
memberMaxx the Axe21-Aug-19 8:41 
GeneralMy vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 2:36
professionalThomas Nielsen - getCore23-Sep-15 2:36 
GeneralRe: My vote of 4 Pin
markmnl23-Sep-15 16:06
membermarkmnl23-Sep-15 16:06 
AnswerRe: My vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 21:50
professionalThomas Nielsen - getCore23-Sep-15 21:50 
GeneralRe: My vote of 4 Pin
markmnl23-Sep-15 22:06
membermarkmnl23-Sep-15 22:06 
AnswerRe: My vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 23:13
professionalThomas Nielsen - getCore23-Sep-15 23:13 
GeneralVery well explained Pin
Ehsan Sajjad16-Sep-15 8:08
mvpEhsan Sajjad16-Sep-15 8:08 
QuestionNot recommended Pin
Godrose5-Sep-15 4:24
memberGodrose5-Sep-15 4:24 
AnswerRe: Not recommended Pin
markmnl5-Sep-15 18:09
membermarkmnl5-Sep-15 18:09 
GeneralRe: Not recommended Pin
Godrose23-Dec-15 22:07
memberGodrose23-Dec-15 22:07 
General6 of this or half dozen of the other Pin
Member 100827673-Sep-15 7:01
memberMember 100827673-Sep-15 7:01 
GeneralRe: 6 of this or half dozen of the other Pin
markmnl3-Sep-15 17:35
membermarkmnl3-Sep-15 17:35 
GeneralI prefer solution #2 Pin
John Brett2-Sep-15 22:16
memberJohn Brett2-Sep-15 22:16 
QuestionIt follows Go principles Pin
Leonid Ganeline31-Aug-15 6:28
professionalLeonid Ganeline31-Aug-15 6:28 
AnswerRe: It follows Go principles Pin
markmnl31-Aug-15 16:02
membermarkmnl31-Aug-15 16:02 
Suggestionsyntactic sugar Pin
John Torjo30-Aug-15 22:14
professionalJohn Torjo30-Aug-15 22:14 
GeneralRe: syntactic sugar Pin
markmnl30-Aug-15 22:20
membermarkmnl30-Aug-15 22:20 
GeneralRe: syntactic sugar Pin
John Torjo2-Sep-15 0:16
professionalJohn Torjo2-Sep-15 0:16 
GeneralRe: syntactic sugar Pin
danielibarnes10-Sep-15 10:17
memberdanielibarnes10-Sep-15 10:17 
GeneralRe: syntactic sugar Pin
John Torjo10-Sep-15 10:22
professionalJohn Torjo10-Sep-15 10:22 
GeneralRe: syntactic sugar Pin
danielibarnes10-Sep-15 11:30
memberdanielibarnes10-Sep-15 11:30 
GeneralRe: syntactic sugar Pin
John Torjo10-Sep-15 12:10
professionalJohn Torjo10-Sep-15 12:10 
QuestionExtremely dangerous approach - there are much better pattern for handling exceptions Pin
svenmatzen30-Aug-15 4:22
membersvenmatzen30-Aug-15 4:22 
AnswerRe: Extremely dangerous approach - there are much better pattern for handling exceptions Pin
markmnl30-Aug-15 15:51
membermarkmnl30-Aug-15 15:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 26 Aug 2015

Tagged as

Stats

64.9K views
34 bookmarked