Return 异常处理中的自定义格式 JSON

Return custom formatted JSON in exception handling

我刚开始将我的项目迁移到 .NET Core 6,使用 ASP.NET 样板和 Kendo 控件。

如果任何数据库操作失败,应用程序将执行一些操作 (insert/update) 并向客户端抛出一些自定义错误消息。

应用程序发送原始错误消息而不是自定义格式 JSON。我是否缺少要配置的内容?

有什么方法可以获取我从控制器返回的自定义错误消息吗?

控制器:

[ValidateAntiForgeryToken()]
[DontWrapResult]
[DisableValidation]
[HttpPost]
public ActionResult CreateOrUpdate([DataSourceRequest] DataSourceRequest request,
                                   [Bind(Prefix = "models")] IEnumerable<InstallationTeamMemberDto> teamMembers,
                                   long id, string teamName, string description, string category, bool isActive,
                                   long? teamLeadId, string contactNumber, string remarks)
{
    List<InstallationTeamMemberDto> teamMembersList = teamMembers.ToList();

    try
    {
        if (ValidateMe(teamMembersList, id, teamName, description, category, isActive, teamLeadId, contactNumber, remarks) && ModelState.IsValid)
        {
            id = _installationTeamAppService.CreateOrUpdateAsync(teamMembersList, id, teamName, description,
                                                                 category, isActive, teamLeadId, contactNumber, remarks);
        }
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", "Unable to Save the data! Internal error occured." + ex.Message.ToString());

        var res1 = teamMembers.ToDataSourceResult(request, ModelState);

        return Json(new
        {
            Data = res1.Data,
            Errors = res1.Errors,
            Id = id,
            IsSuccess = 0
        }, JsonSetting.DefaultJsonSerializerSetting);
    }

    var res = teamMembers.ToDataSourceResult(request, ModelState);

    // Returning the Id to save the Technical Details information
    return Json(new
    {
        Data = res.Data,
        Errors = res.Errors,
        Id = id,
        IsSuccess = 1
    }, JsonSetting.DefaultJsonSerializerSetting);
}

结果:

ASP.NET 样板文件的 Conventional Unit of Work 范围围绕您的控制器操作。

您需要将 try/catch 放在工作单元范围内:

[UnitOfWork(IsDisabled = true)]                      // Add this
public ActionResult CreateOrUpdate(...)
{
    List<InstallationTeamMemberDto> teamMembersList = teamMembers.ToList();

    try
    {
        using (var uow = _unitOfWorkManager.Begin()) // Add this
        {                                            //
            if (ValidateMe(...)
            {
                id = _installationTeamAppService.CreateOrUpdate(...);
            }
            uow.Complete();                          // Add this
        }                                            //
    }
    ...
}

您可以在应用程序服务方法上添加一个 [UnitOfWork] 属性,而不是在您的控制器中显式开始一个工作单元:

[UnitOfWork] // Add this
public void CreateOrUpdate(...)

您可以要求一个新的工作单元,但您将拥有不必要的环境工作单元:

// [UnitOfWork(IsDisabled = true)]                                                     // -
public ActionResult CreateOrUpdate(...)
{
    List<InstallationTeamMemberDto> teamMembersList = teamMembers.ToList();

    try
    {
        // using (var uow = _unitOfWorkManager.Begin())                                // -
        using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) // +
        {
            if (ValidateMe(...)
            {
                id = _installationTeamAppService.CreateOrUpdate(...);
            }
            uow.Complete();
        }
    }
    ...
}