简体   繁体   中英

Trying to show exception message in UI controller in ASP.NET MVC

In the configuration file I have made it so that the property Name of the class Series IsUnique() so whenever I try to add another entity with the same name, I get a DbUpdateException . I can access the message of this exception everywhere except for the UIController .

Here we have the code in my service where I check if the series is valid and if not I throw an exception (I know this is not best practice put at this point I just want it to work first)

public void Add(SeriesDTO series)
{
    if (series.Name != null && series.Startdate < series.Enddate)
    {
        _unitOfWork.Series.AddAsync(_mapper.Map<SeriesDTO, Series>(series));
        _unitOfWork.CommitAsync();                          
    }
    else 
        throw new Exception("Series data is not valid");
}

Then I have my controller where I check for the DbUpdateException and if I find it I throw another exception this I prefer not to do because at this point I can access this exception message with the right message.

[HttpPost("add")]
//POST: series/add
public IActionResult Add(SeriesDTO series)
{
    try
    {
        _seriesService.Add(series);
    }
    catch (DbUpdateException E)
    {
        throw new Exception("Series with this name already exists.");
    }

    return Ok(series);
}

Up until this point I can always access the exception error but when I get to my UI controller then this exception turns into a 500 internal server error and thus I can not differentiate between an invalid entity exception and a DbUpdateException and thus cannot access the right message.

public IActionResult Add(SeriesDTO serie)
{
    if(serie.Enddate < DateTime.Today || serie.Enddate.Equals(null))
    {
        serie.Active = false;
    }
    else
    {
        serie.Active = true;
    }
            
    try
    {
        string data = JsonConvert.SerializeObject(serie);
        var result = _client.UploadString("series/add", data);
    }
    catch(Exception E)
    {
        ExceptionModel Exception = new ExceptionModel("Something went wrong with the series data.");
        return View("Exception", Exception); 
        //return View("Create");
    }    

    return Redirect("Index");
}

Does anyone know how to properly send the exception through to the UI controller?

You can do that.

In you Controller method:

public IActionResult Add(SeriesDTO serie)
{
   //...
   ModelState.AddModelError("CustomError", "You error message as string.");
   //...
}

And in you view you need that:

<span asp-validation-for="CustomError" class="text-danger"></span>

If something doesn't work, tell me and edit you post with the code of you View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM