Elisabeth
Elisabeth

Reputation: 21206

What kind of error codes should a repository return to a RESTful Web API

When I look at Microsofts sample about the repository pattern its of course a total simple sample nothing to do with the real world requirements - as always...-

http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

The Repository Add/Del/Update methods return Void - nothing -

On the other side when someone uses my RESTful Web API I want to offer things like

NotFound() if the deletion of a record did not do anything

OK() If the deletion was successful

Same for Update method.

What do you use in your real world projects as return types for your repositories to let the caller know what really happened?

Upvotes: 3

Views: 1965

Answers (2)

CodeCaster
CodeCaster

Reputation: 151584

What do you use in your real world projects as return types for your repositories to let the caller know what really happened?

A "result object". A simple version could look like this:

public class RepositoryActionResult
{
    public int RecordsAffected { get; set; }        
}

Then you can set that from your repository methods and handle the results from calling code appropriately, without using exceptions for control flow.

You can make this class as complex as you want, depending on your requirements.

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156504

There are two major options:

  1. Treat situations like NotFound as exceptional. Specify exception types that will be thrown by your repository in situations where the object you meant to delete wasn't there. If you choose this option, then you can have a very general exception-catching handler at the Web API layer that knows what sort of response these exceptions should translate to.
  2. Change the repository interface to return an Optional error value or a Sum Type representing all the possible results of the call to that method. This requires the method calling into the repository to decide what to do in each scenario, but it allows more flexibility in handling scenarios as well. (e.g. Perhaps you want DeletePerson to return NotFound if the person itself wasn't there, but if no data is present when you use a different repository to clean up some related data, you want to use a different return type?)

What you should avoid is having the Repository layer return some kind of HTTP-oriented response code.

Upvotes: 2

Related Questions