Click here to Skip to main content
15,887,175 members
Articles / Programming Languages / C# 5.0

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

Rate me:
Please Sign up or sign in to vote.
4.66/5 (47 votes)
26 Aug 2015CPOL3 min read 96.9K   34   53
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.

Update June 2023: Published NuGet package FalconWare.ErrorHandling

Problem

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

C#
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:

C#
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.:

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

And in our FileStorageService from earlier:

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

And our caller could:

C#
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 that's 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>:

C#
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:

C#
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:

C#
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 returned OperationResult.

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

History

27 August 2015 - Initial Version

License

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


Written By
Zimbabwe Zimbabwe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
zilongkk22-Jul-18 0:29
zilongkk22-Jul-18 0:29 
GeneralRe: My vote of 1 Pin
Maxx the Axe21-Aug-19 7:41
Maxx the Axe21-Aug-19 7:41 
GeneralMy vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 1:36
professionalThomas Nielsen - getCore23-Sep-15 1:36 
GeneralRe: My vote of 4 Pin
markmnl23-Sep-15 15:06
markmnl23-Sep-15 15:06 
AnswerRe: My vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 20:50
professionalThomas Nielsen - getCore23-Sep-15 20:50 
GeneralRe: My vote of 4 Pin
markmnl23-Sep-15 21:06
markmnl23-Sep-15 21:06 
AnswerRe: My vote of 4 Pin
Thomas Nielsen - getCore23-Sep-15 22:13
professionalThomas Nielsen - getCore23-Sep-15 22:13 
GeneralVery well explained Pin
Ehsan Sajjad16-Sep-15 7:08
professionalEhsan Sajjad16-Sep-15 7:08 
QuestionNot recommended Pin
Godrose5-Sep-15 3:24
Godrose5-Sep-15 3:24 
AnswerRe: Not recommended Pin
markmnl5-Sep-15 17:09
markmnl5-Sep-15 17:09 
GeneralRe: Not recommended Pin
Godrose23-Dec-15 21:07
Godrose23-Dec-15 21:07 
General6 of this or half dozen of the other Pin
Member 100827673-Sep-15 6:01
Member 100827673-Sep-15 6:01 
It looks to me like what this does is take a bunch of information delivered about an Exception, repackage it into a container class, and as a result, instead of the programmer doing a

try{}catch{extract info from Exception}

the programmer does a if(){}else{extract information from container class}

The data either way is essentially the same. With try-catch one gets an Exception, with if-else one gets a Success property. The NonSuccessMessage property is a string unpacking properties of the Exception, which is what a developer would do with the try-catch method.

I personally don't see the huge benefit, but I do see the danger warnings already raised. Exception handling is hard because there are general classes of exceptions that are often handled at different levels of code. Boneheaded exceptions should be allowed to be raised so they break the program and can be found and fixed. For example, indexing off the end of an array should never be allowed to happen, but often does until discovered and fixed, even by very experienced developers. Making container classes to capture these is, in my estimation, a waste of effort. Use the built in Exceptions and rid your code of them.

The level of these types of errors is often localized in a function. These should be captured and fixed within these localized levels.

Thinking in general about Exception handling, it seems like there are levels of Exception handling. Say a function calls into System.IO and does directory or file handling. In my way of thinking, this is not localized as much, and the exception might be generated by the called class and not the calling class. But the calling class must handle it. The exception might occur due to a permission problem say, or due to file access violation. What does the programmer do with these under normal try-catch circumstances? He or she looks into the exception and figures out what needs to happen based on the underlying cause: permission versus access versus lock, etc.

That is standard exception/debugging behavior. It would happen whether doing a boring old try-catch or your if-else. Both would require a programmer to look into the underlying cause to understand what happened. If a programmer needed to take specific action on a specific type of error, say file not existing, then catching that specific type of error would allow him or her to do something like give the client a chance to create the missing file. Using very specific Exceptions seems OK for developing/debugging, and for taking very specific actions. At some point, however, presumably the code goes to the client who is not a developer, and probably not technically savvy, and who probably should never be given straight Exception verbiage.

How should the code handle Exceptions the clients are likely to encounter?

Is this another level of exceptions? Errors the programmer has no control over, were not anticipated, and are not expressly coded for with specific Exception types. Programmers could write classes that call into the network handling classes, for example, so that the calling class catches specific exceptions, but how does code handle it when the server that is never expected to be down is down temporarily for a patch? Whoops. The program crashes with an exception in the face of the client. Here I think it perfectly OK to try-catch the top-most general Exception class, but this is not at the localized function level, nor at the cross-class calling level, but at the top-most application level.
GeneralRe: 6 of this or half dozen of the other Pin
markmnl3-Sep-15 16:35
markmnl3-Sep-15 16:35 
GeneralI prefer solution #2 Pin
John Brett2-Sep-15 21:16
John Brett2-Sep-15 21:16 
QuestionIt follows Go principles Pin
Leonid Ganeline31-Aug-15 5:28
professionalLeonid Ganeline31-Aug-15 5:28 
AnswerRe: It follows Go principles Pin
markmnl31-Aug-15 15:02
markmnl31-Aug-15 15:02 
Suggestionsyntactic sugar Pin
John Torjo30-Aug-15 21:14
professionalJohn Torjo30-Aug-15 21:14 
GeneralRe: syntactic sugar Pin
markmnl30-Aug-15 21:20
markmnl30-Aug-15 21:20 
GeneralRe: syntactic sugar Pin
John Torjo1-Sep-15 23:16
professionalJohn Torjo1-Sep-15 23:16 
GeneralRe: syntactic sugar Pin
danielibarnes10-Sep-15 9:17
danielibarnes10-Sep-15 9:17 
GeneralRe: syntactic sugar Pin
John Torjo10-Sep-15 9:22
professionalJohn Torjo10-Sep-15 9:22 
GeneralRe: syntactic sugar Pin
danielibarnes10-Sep-15 10:30
danielibarnes10-Sep-15 10:30 
GeneralRe: syntactic sugar Pin
John Torjo10-Sep-15 11:10
professionalJohn Torjo10-Sep-15 11:10 
QuestionExtremely dangerous approach - there are much better pattern for handling exceptions Pin
svenmatzen30-Aug-15 3:22
svenmatzen30-Aug-15 3:22 
AnswerRe: Extremely dangerous approach - there are much better pattern for handling exceptions Pin
markmnl30-Aug-15 14:51
markmnl30-Aug-15 14: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.