Home > OS >  Net5 mysql Access Duplicate ErrorCode
Net5 mysql Access Duplicate ErrorCode

Time:10-13

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

CodePudding user response:

Sorry, I'd rather comment but I still cannot. You may try to catch an Exception object which has a InnerException attribute. Also, you may also check DbEntityValidationException class.

Reference: link

CodePudding user response:

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.ToString() == "DuplicateKeyEntry")
                {
                    return ErrorMessages.RecordExists;
                } else
                {
                    return ErrorMessages.UnknownError;
                }
            }
            return message;
        }
    }
  • Related