0

I am using the following code in my controller when I submit a new entry:

    // POST /api/Content/
    public HttpResponseMessage PostContent(Content content)
    {
        try
        {
            content.ModifiedDate = DateTime.Now;
            _uow.Contents.Add(content);
            _uow.Commit();
            var response = Request.CreateResponse<Content>(HttpStatusCode.Created, content);
            return response;
        }
        catch (DbUpdateException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
        } 
    }

This only picks up DbUpdateExceptions so if there is another kind of exception then I think I need to handle it differently.

Can anyone suggest how I should handle other exceptions?

  • Try separating your layers so that your DataAccess layer can catch it's own errors, log them and throw a friendly message or more general exception to the caller. From there you can catch that error and do with as you choose. – CD Smith Jul 23 '13 at 14:44
  • 1
    http://stackoverflow.com/questions/15167927/how-do-i-log-all-exceptions-globally-for-a-c-sharp-mvc4-webapi-app – qujck Jul 23 '13 at 15:10
  • *Can anyone suggest how I should handle other exceptions?* Handle the ones that you can meaningfully (e.g. `DbUpdateException`) but otherwise [use the `HandleErrorAttribute`](http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.108).aspx) for MVC. – ta.speot.is Jul 28 '13 at 06:55

2 Answers2

2

You can add several catch in a row going from the most particular to most general

try
{
      content.ModifiedDate = DateTime.Now;
      _uow.Contents.Add(content);
      _uow.Commit();
      var response = Request.CreateResponse<Content>(HttpStatusCode.Created, content);
      return response;
}
catch (DbUpdateException ex)
{
     return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
} 
catch (Exception ex)
{
     // do what you want
} 
Dima
  • 6,721
  • 4
  • 24
  • 43
Hassan
  • 1,413
  • 1
  • 10
  • 12
0

If we want to move from quick-and-dirty method to longer-but-safer, we may pass following steps:

  1. Excapsulate data access in separate object and handle it's exceptions in it, passing to the outside world custom exceptions. You may decide to hide all data access exceptions under single custom exception.

  2. (as @Massanu pointed) Concatenate handlers starting with most particular to most general. To react approprietely on different exceptions, do not use single catch (Exception ex) handler.

  3. If something, actually, let unhandled, you may catch it in Application_Error method of global.asax: http://msdn.microsoft.com/ru-ru/library/24395wz3(v=vs.100).aspx

There is a good chapter about error handling in Code Complete book written by Steve Macconell: http://cc2e.com/

Dima
  • 6,721
  • 4
  • 24
  • 43