0

I'm trying to show a Duplicate Record error message in an WebAPI service. I'm using .net5 and mysql. I cannot seem to find a way to pull the duplicateEntry message from the exception response. I'd like to key in on the ErrorCode field and use this to tailor a response to the user. I can see the Message property, but cannot figure out how to access the innerException.

        {
            try
            {
                module.Id = Guid.NewGuid();
                await _moduleRepository.Add(module);
                await _uow.CompleteAsync();
                return true;
            }
            catch (DbUpdateException ex)
            {

                logger.LogWarning("Module - Add Error: " + ex.Message);
                return false;
            }
            
            
        } 

enter image description here

a2ron44
  • 1,711
  • 1
  • 13
  • 18
  • What does your code actually do? EF Core doesn't have `Repository` or `UoW` classes - it doesn't need them because a DbContext is already a multi-entity UoW, a DbSet is already a single entity Repository. EF Core when used properly will handle persisting existing objects just fine without having to specify whether it's new or not - a newly attached object with a non-empty PK will be updated, an object with an empty PK will be inserted – Panagiotis Kanavos Oct 15 '21 at 13:33
  • Which means, that `module.Id = Guid.NewGuid();` is actually a bug. You should let the database generate the PK. On the other hand, GUIDs are *horrible* primary keys because they have no meaningful order and end up causing index fragmentation. You'd need to generate a sequential GUID to avoid ordering and fragmentation problems – Panagiotis Kanavos Oct 15 '21 at 13:34
  • Finally - how did you end up with a Duplicate error when using a GUID as a key? – Panagiotis Kanavos Oct 15 '21 at 13:36
  • There is a unique index on a Name column. – a2ron44 Oct 15 '21 at 17:53

2 Answers2

0

You may try to catch an Exception object which has a InnerException attribute. Also, you may also check DbEntityValidationException class.

Reference: link

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Hackjaku
  • 84
  • 1
  • 10
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 12 '21 at 16:34
0

Found something that worked. Made a helper function, but this is highly coupled to Mysql. Had to check the InnerException to see if it was of type MsyqlException.

    {
        public static string GetExceptionMessage(Exception ex)
        {
            var message = ex.Message;
            var innerException = ex.InnerException;
            if (innerException != null && (innerException.GetType() == typeof(MySqlException)))
            {
                var dbException = (MySqlException)innerException;
                if(dbException.ErrorCode == MySqlErrorCode.DuplicateKeyEntry)
                {
                    return ErrorMessages.RecordExists;
                } else
                {
                    return ErrorMessages.UnknownError;
                }
            }
            return message;
        }
    }
a2ron44
  • 1,711
  • 1
  • 13
  • 18
  • 1
    You could replace the if with while, because innner can also have inner and you don’t know which level is good for you. – Vivek Nuna Oct 12 '21 at 19:28
  • 1
    Note that you can write `if(dbException.ErrorCode == MySqlErrorCode.DuplicateKeyEntry)` instead of relying on `ToString()` and a string comparison. – Bradley Grainger Oct 13 '21 at 04:57
  • Thanks! I revised solution to use the constant. – a2ron44 Oct 15 '21 at 13:27
  • @a2ron44 that will tell you what the symptom is, not fix the real bugs in the code. If you use EF Core properly it will handle attached objects by either inserting or updating them based on the PK value. In this case though, how did you end up with a DuplicateKeyEntry error when using a GUID? – Panagiotis Kanavos Oct 15 '21 at 13:36