我正在尝试在NET Core WEB API中实现GlobalExceptionFilter。 这是我的过滤器代码:
public class GlobalExceptionFilter : IExceptionFilter, IDisposable
{
private readonly ILogger _logger;
public GlobalExceptionFilter(ILoggerFactory logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
this._logger = logger.CreateLogger("Global Exception Filter");
}
public void Dispose()
{
}
public void OnException(ExceptionContext context)
{
Dictionary<string, string> data = new Dictionary<string, string>();
HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
String message = String.Empty;
var ex = context.Exception;
TypeSwitch.Do(ex,
TypeSwitch.Case<ArgumentException>(() => { statusCode = HttpStatusCode.BadRequest; }),
TypeSwitch.Case<ArgumentNullException>(() => { statusCode = HttpStatusCode.BadRequest; }),
TypeSwitch.Case<ArgumentOutOfRangeException>(() => { statusCode = HttpStatusCode.BadRequest; }),
TypeSwitch.Case<KeyNotFoundException>(() => { statusCode = HttpStatusCode.NotFound; }),
TypeSwitch.Case<DivideByZeroException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; }),
TypeSwitch.Case<QueryFormatException>(() => { statusCode = HttpStatusCode.MethodNotAllowed; })
);
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)statusCode;
response.ContentType = "application/json";
var err = new ErrorPayload()
{
Data = data,
StackTrace = ex.StackTrace,
Message = ex.Message,
StatusCode = (int)statusCode
};
response.WriteAsync(JsonConvert.SerializeObject(err));
}
}
这是我在
中的初始化代码public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc( config =>
{
config.Filters.Add(typeof(GlobalExceptionFilter));
}
);
}
我正在测试这种控制器方法中的错误处理
[HttpGet("{idCliente}")]
public IActionResult GetCliente(int idCliente)
{
throw new QueryFormatException("My Custom Exception");
}
有什么想法吗?谢谢!
更新
好吧,我不得不承认我认为那是行不通的,因为Postman向我显示了连接错误,而不是NotFound的MethodNotAllowed(404)。按照建议,我检查调试和状态响应,并且实际是期望值。