General error handling

Hi all!
I would like to know which is the best way to handle a general, app-level error system; I find myself to reuse this code for each error response:

            var responseDto = new ErrorResponse
            {
                ResponseStatus = new ResponseStatus
                {
                    ErrorCode = "my error code",
                    Message = "my response message"
                }
            };

            return new HttpError(HttpStatusCode.NotFound, "Not Found")
            {
                Response = responseDto
            }; 

Should I put it in a class and recall it from each service? Should I write an Interface system like the LogManager does?
Thank you!

For returning a 404 I’ll just:

throw HttpError.NotFound("User does not exist");

Hi mythz, yes… I know I can use it… but if I don’t specify the responseDto it reports me something like:

{"ResponseStatus":{"ErrorCode":"Not Found","Message":"Not Found","Errors":[]}}

I would to have more control on this output so I’m using this:

            var responseDto = new ErrorResponse
            {
                ResponseStatus = new ResponseStatus
                {
                    ErrorCode = "my error code",
                    Message = "my response message"
                }
            };

            return new HttpError(HttpStatusCode.NotFound, "Not Found")
            {
                Response = responseDto
            };

I would like to know which is the best way to reuse this code in my project.

It also more importantly populates the HTTP Response Status and description which is most of the time the only thing HTTP clients need to look at. They know a 404 means that what they requested doesn’t exist and can handle it in the most appropriate way for their app.

As for DRY code, treat it just like any other C# code you want to reuse. There’s nothing special about ServiceStack classes, refactor out the common parts into a method just as you would normally, my pref is to use readable extension methods, but use whatever you’re comfortable with.

I’m generally a newbie with C# code design… the solution I found is to declare for each service a new custom class that handle error responses:

private static CustomError responder = new CustomError();

Than I call the methods where I need like this:

responder.NotFound("my cusom message");

Could be a performance problem reinitialize the class for each service?

No it wont have any noticeable impact on performance. Also a static instance is only ever initialized once, however I don’t see any benefit of having a private static instance per class vs just calling a static method:

CustomError.NotFound("my custom message");

But it’s not going to be noticeable either way, although I’d always recommend the least code option where available.

Yes mythz, you’re definitely right… I realized it just after I posted the comment!
I will use your solution for sure.

Thank you!