C#C
C#3y 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");
}
imagen.png
Was this page helpful?