public class GlobalExceptionFilter : IExceptionFilter
{
readonly ILogger _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
_logger.LogError(context.Exception, context.Exception.Message);
if (context.Exception is ShowMessageException)
{
context.Result = new JsonResult(context.Exception.Message);
}
else
{
context.Result = new JsonResult("服务器异常");
}
context.ExceptionHandled = true;
}
}
public class ShowMessageException : Exception
{
public ShowMessageException(string message) : base(message)
{ }
}
public void ConfigureServices(IServiceCollection services)
{
//filters
services.AddScoped<GlobalExceptionFilter>();
}