gpt4 book ai didi

c# - Angular 在 ASP.NET MVC 之上,显示错误

转载 作者:太空狗 更新时间:2023-10-29 22:22:16 24 4
gpt4 key购买 nike

我们正在现有的 asp.net c# MVC 应用程序上放置一个 Angular 前端。在我们的服务器代码中,我们广泛使用自定义异常来返回业务规则错误。

是否有最佳实践或最巧妙的方法来处理 mvc Controller 或 webApi Controller 上的异常(实际上是从业务层向上推)并将其转换为 Angular 并将其显示在“用户错误”弹出窗口中?人们如何解决这个问题?

最佳答案

其他人已经给出了很好的答案,但我想详细说明我的方法,因为我想它将涵盖两端(前端和服务器)并提供更多细节。

这是我在 WebAPI + AngularJS 应用程序中处理错误和异常的完整方法。

第 1 步. 服务器端的 WebApi Controller

我有一个特定的 DTO 用于向客户端传达验证错误,因为我相信它们不同于Exception。异常将导致 500 错误,其中验证结果应导致 400(错误请求)错误。

所以,这是我的 ApiValidationResult 类:

public class ApiValidationResult
{
public List<ApiValidationError> Errors { get; set; }

public static ApiValidationResult Failure(string errorKey)
{
return new ApiValidationResult {Errors = new List<ApiValidationError> {new ApiValidationError(errorKey)}};
}

// You can add a bunch of utility methods here
}

public class ApiValidationError
{
public ApiValidationError()
{
}

public ApiValidationError(string errorKey)
{
ErrorKey = errorKey;
}

// More utility constructors here

public string PropertyPath { get; set; }
public string ErrorKey { get; set; }
public List<string> ErrorParameters { get; set; }
}

我总是为 WebApi(和 MVC) Controller 使用我自己的基类,所以我可以使用它们来添加方便的结果方法,例如:

public abstract class ExtendedApiController : ApiController
{
protected IHttpActionResult ValidationError(string error)
{
return new ValidationErrorResult(ApiValidationResult.Failure(error), this);
}

// More utility methods can go here
}

它使用我专门为此目的创建的自定义 IHttpActionResult:

public class ValidationErrorResult : NegotiatedContentResult<ApiValidationResult>
{
public ValidationErrorResult(ApiValidationResult content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
: base(HttpStatusCode.BadRequest, content, contentNegotiator, request, formatters)
{
}

public ValidationErrorResult(ApiValidationResult content, ApiController controller)
: base(HttpStatusCode.BadRequest, content, controller)
{
}
}

因此,我可以在我的 Controller 操作中干净利落地使用这样的代码:

    [HttpPost]
public IHttpActionResult SomeAction(SomeInput input)
{
// Do whatever...
if (resultIsValid)
{
return Ok(outputObject);
}

return ValidationResult(errorMessage);
}

第 2 步. 处理意外异常

正如我所说,我相信只有真正未处理的 Exception 才会导致 500(内部服务器错误)响应。

WebApi 会自动将此类未处理的异常转换为 500 结果。我唯一需要做的就是记录它们。因此,我创建了一个 IExceptionLogger 接口(interface)的实现并像这样注册它:

GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new UnhandledExceptionLogger());

第 3 步。在客户端拦截和显示错误

AngularJS 允许拦截所有从 $http 服务发送的 HTTP 调用。我用它来集中所有消息弹出窗口。这是我的拦截器代码:

appModule.factory("errorsHttpInterceptor", [
"$q", "$rootScope", "$injector",
($q: ng.IQService, $rootScope: IAppRootScopeService, $injector) => {
return {
'responseError': rejection => {
// Maybe put the error in $rootScope and show it in UI
// Maybe use a popup
// Maybe use a 'toast'
var toastr = $injector.get('toastr');
toastr.error(...);

return $q.reject(rejection);
}
};
}
]);

您可以在拦截器中做各种事情,例如记录调试消息,或应用键来显示错误代码的字符串转换。您还可以区分 500 和 400 错误,并显示不同类型的错误消息。

我使用 toastr 库,我认为它显示了一个不错的 UI,并且在 API 级别上非常方便。

最后,我这样注册拦截器:

appModule.config([
'$httpProvider',
($httpProvider: ng.IHttpProvider) => {
$httpProvider.interceptors.push('errorsHttpInterceptor');
}
]);

语法在 TypeScript 中,与 JavaScript 非常相似,我相信您能理解它的含义。

关于c# - Angular 在 ASP.NET MVC 之上,显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29851891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com