C
C#2y ago
XD

❔ (MVC web app) How can I handle exceptions/errors in this case?

So I was thinking of placing all this code (the one inside the function) inside a try catch block, and in the catch statement, if there's an exception catch it and then display an error message such as "Something went wrong, error #0001", is it bad practice? what could i do instead?
public IActionResult AddTransaction(Models.Transaction transaction, CategoryViewModel cvm)
{
var userId = transaction.UserId;
var findUserTask = _userManager.FindByIdAsync(userId);

Task.WaitAll(findUserTask);

var user = findUserTask.Result;

if (user == null)
{
return RedirectToPage("/Account/Login", new { area = "Identity" });
}

decimal transactionValue = transaction.Value;

transactionValue = decimal.Parse(transactionValue.ToString());

var categories = _categoryService.GetAllCategories();
var transactions = _transactionService.GetAllTransactions();

var transactionCategory = categories.Where(c => c.Id == transaction.CategoryId).First();

//transactionCategory.TotalValue += transaction.Value;

var selectedCurrencyOption = JsonSerializer.Deserialize<Currency>(cvm.CurrencyObjectJson);

transaction.CurrencyCode = selectedCurrencyOption.CurrencyCode;
transaction.CurrencyNativeSymbol = selectedCurrencyOption.NativeSymbol;

_transactionService.AddTransaction(transaction);
_context.SaveChanges();

ChangeUserCategoryValue(user, transactionCategory.Name, transactionValue).Wait();

user = findUserTask.Result;

Currency currencyObject = new Currency
{
CurrencyCode = user.CurrencyCode,
NativeSymbol = user.CurrencyNativeSymbol,
Name = string.Empty
};

string currencyJson = JsonSerializer.Serialize(currencyObject);
UpdateCurrency(currencyJson);

return Redirect("https://localhost:7229");
}
public IActionResult AddTransaction(Models.Transaction transaction, CategoryViewModel cvm)
{
var userId = transaction.UserId;
var findUserTask = _userManager.FindByIdAsync(userId);

Task.WaitAll(findUserTask);

var user = findUserTask.Result;

if (user == null)
{
return RedirectToPage("/Account/Login", new { area = "Identity" });
}

decimal transactionValue = transaction.Value;

transactionValue = decimal.Parse(transactionValue.ToString());

var categories = _categoryService.GetAllCategories();
var transactions = _transactionService.GetAllTransactions();

var transactionCategory = categories.Where(c => c.Id == transaction.CategoryId).First();

//transactionCategory.TotalValue += transaction.Value;

var selectedCurrencyOption = JsonSerializer.Deserialize<Currency>(cvm.CurrencyObjectJson);

transaction.CurrencyCode = selectedCurrencyOption.CurrencyCode;
transaction.CurrencyNativeSymbol = selectedCurrencyOption.NativeSymbol;

_transactionService.AddTransaction(transaction);
_context.SaveChanges();

ChangeUserCategoryValue(user, transactionCategory.Name, transactionValue).Wait();

user = findUserTask.Result;

Currency currencyObject = new Currency
{
CurrencyCode = user.CurrencyCode,
NativeSymbol = user.CurrencyNativeSymbol,
Name = string.Empty
};

string currencyJson = JsonSerializer.Serialize(currencyObject);
UpdateCurrency(currencyJson);

return Redirect("https://localhost:7229");
}
No description
18 Replies
Angius
Angius2y ago
Ooof ouch owie that .Result Use proper async code pls For exceptions, you'd usually rely on the exception handling middleware
softmek
softmek2y ago
In the provided AddTransaction method, it seems there's a need for improvements related to asynchronous operations, exception handling, and code structure. Here's an enhanced version with comments to illustrate some changes:
XD
XDOP2y ago
sorry thank you for your answer, so it is okay to use a try catch block for all the code?
softmek
softmek2y ago
💯 . I have over 7 year experience and that's the best way you will ever handle that, but avoid absolute url inside your application https://www.linkedin.com/in/haron-njuguna/
XD
XDOP2y ago
yeah, will fix it, thank you so much!
softmek
softmek2y ago
If you get stuck, You can always reach out in my DM. especially ln
XD
XDOP2y ago
btw i was thinking of redirecting to the same view but changing the red <p> as i showed here if there was an error, do you think it is better than redirecting to an error view? @softmek
softmek
softmek2y ago
You can use alert message for that. Imagine all cards didn’t load, the page will be well written in red haha! 😛 Which FE framework are you using, i can suggest what I use
XD
XDOP2y ago
i'm not proficient in any framework yet so i'm just using html with razor
XD
XDOP2y ago
that is amazing it should be shown after reloading the page right?
softmek
softmek2y ago
When an error occurs display the alert which will disappear in few seconds
softmek
softmek2y ago
For the dates, you can checkout https://momentjs.com/docs/, Whatever you have done will be greatly affected by timezones
No description
XD
XDOP2y ago
alright, thank you man, i really appreciate your help!
softmek
softmek2y ago
No problem man, am off the grid! it's late 3:15am here, you can hit me up in linkedin haha, 👌🏾
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?