using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; using System; using QualityControlPlatform.Helpers.Nlog; using QualityControlPlatform.Helpers.Response; namespace QualityControlPlatform.Controllers.Base { /// /// 全局异常返回 /// [Route("error")] [ApiController] public class ErrorController : ControllerBase { /// /// 全局错误返回 /// /// [HttpGet] public ActionResult Index() { //UseExceptionHandler中间件中拦截到异常时,会将异常信息保存在请求上下文中,所以我们可以从HttpContext中拿到ExceptionHandler的异常信息: var feature = HttpContext.Features.Get(); if (feature == null) return ResponseHelper.ServerError(); var exception = feature.Error; LogHelper.Log.Error(exception); Console.WriteLine("【ERROR】" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + exception.Message); // todo:调用日志组件记录异常信息,或对异常做多路判断 return ResponseHelper.ServerError(); } } }