C
C#13mo 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
Angius13mo ago
Ooof ouch owie that .Result Use proper async code pls For exceptions, you'd usually rely on the exception handling middleware
softmek
softmek13mo 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
XDOP13mo ago
sorry thank you for your answer, so it is okay to use a try catch block for all the code?
softmek
softmek13mo 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
XDOP13mo ago
yeah, will fix it, thank you so much!
softmek
softmek13mo ago
If you get stuck, You can always reach out in my DM. especially ln
XD
XDOP13mo 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
softmek13mo 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
XDOP13mo ago
i'm not proficient in any framework yet so i'm just using html with razor
XD
XDOP13mo ago
that is amazing it should be shown after reloading the page right?
softmek
softmek13mo ago
When an error occurs display the alert which will disappear in few seconds
softmek
softmek13mo ago
For the dates, you can checkout https://momentjs.com/docs/, Whatever you have done will be greatly affected by timezones
No description
XD
XDOP13mo ago
alright, thank you man, i really appreciate your help!
softmek
softmek13mo ago
No problem man, am off the grid! it's late 3:15am here, you can hit me up in linkedin haha, 👌🏾
Accord
Accord13mo 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.
Want results from more Discord servers?
Add your server