How to return -1 in catch block.
See original GitHub issueI’m trying to catch the DbUpdateConcurrencyException and return -1:
var number = await _numberingManager.GetNumberByName(profileName).FirstOrDefaultAsync();
try
{
if (number != null)
{
await Task.Delay(delay);
NextNumber(number);
await CurrentUnitOfWork.SaveChangesAsync();
return number.LastUsedNumber;
}
else
{
throw new UserFriendlyException(string.Format("Record not found: {0}", profileName));
}
}
catch (DbUpdateConcurrencyException ex)
{
return -1;
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
But I keep getting even I return -1:
{
"result": null,
"targetUrl": null,
"success": false,
"error": {
"code": 0,
"message": "An internal error occurred during your request!",
"details": null,
"validationErrors": null
},
"unAuthorizedRequest": false,
"__abp": true
}
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions. —> System.Data.Entity.Core.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
I wonder to know how to return -1 instead of the error message.
Issue Analytics
- State:
- Created 6 years ago
- Comments:12 (5 by maintainers)
@KennyEng12 It is because when
catch( DbUpdateConcurrencyException ex) { return -1; }
did catch the exception, the changes to the entities still remain intact. Therefore, when exiting the method,Abp.WebApi.Uow.AbpApiUowFilter
will try to complete the UOW and save any changes made to the entities into the dbIf you want to handle the
DbUpdateConcurrencyException
in your method, i would suggest that you begin a new UOW scope (usingIUnitOfWorkManager
) to encapsulate all your code that changes the entities, then place thetry/catch
around the new UOW scope.@ryancyq Thanks for the suggestion.