2

I have a problem in HotTowel template. how can I catch sql duplicate unique key value exception in breeze js and display that?

my controller:

[BreezeController]
    [System.Web.Http.Authorize]
    public partial class DataServiceController : ApiController
    {
        [System.Web.Http.HttpPost]
        public SaveResult SaveChanges(JObject saveBundle)
        {
            SaveResult result;
            try
            {
                result = this._contextProvider.SaveChanges(saveBundle, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
    }
Nima
  • 33
  • 3

1 Answers1

1

When the database returns that error, it's hard to match it up to the entity that caused the problem becase MSSQL doesn't tell you much. One can do something like this:

catch (Exception ex)
{
    // if a "duplicate key" exception, extract the table name
    var match = Regex.Match(ex.Message, "duplicate key.* object '([^']*)'");
    if (match.Success)
    {
        var table = match.Groups[1].Value; // dbo.Customer
        var entityType = table.Split('.').Last(); // Customer
        throw new HttpException(409, "Duplicate key saving entity " + entityType, ex);
    }
    throw ex;
}

So that you get a 409 Conflict response code and the type of the entity that caused the problem.

Steve Schmitt
  • 3,124
  • 12
  • 14