Click here to Skip to main content
15,887,485 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 
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 
Using "The Operation Result Approach" is all but "SOLID" - you are shifting the responsibility to interpret a result as an exception to the caller rather than the executing code. This way the code is not "fail-safe" any more: when you don't implement explicit checks for the exception on the caller side, your code will not abort operation, but simply continue with a wrond result (e.g. returning NULL instead of failing when performing a security check or a part of a financial transaction). An exception is much more than just a "hint" that something "might" went wrong. Even a simple http-timeout cannot be handled by simply reissuing the request: the http-request might timeout while writing to the database inside that request might have been successfully, so that a 2nd try might insert additional (and in this case WRONG) data - you might create a 2nd payment record.

Instead your service contract must clearly state what type of exception are acceptable for an implementation to throw and these are the exceptions a caller must handle (or fail). Not implementing anything special and simply throwing away the result of a method call MUST NOT pose the risk of hiding problems. Returning an "exception"-object instead of throwing an exception violates that and introduces a high risk of messing up the whole business process.

Implementing your "Operation Result Approach" implies that developers that use it do know when to use use it and when not to use it. This needs to be weighted against the gains of this approach. Your approach changes a "try-catch" to a "if-else" - I would say: that's not really a great benefit, but it's a really great risk.

If you know the call can bee repeated without risk of data-corruption: implement a retry policy. If you implement an interface that does not document that a timeout exception might be thrown, catch the possible timeout exception where it might happen and handle it there or encapsulate it into something like a BusinessException("Timeout Exception", PossibleUserAction.Retry, ex) with being "PossibleUserAction" an enum with members like "Retry", "CallAdministrator", "NoActionRequired", etc. and handle the BusinessException at the calling side (for example at the UI by displaying an appropriate message to the user).
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.