NetCore项目实战篇02---全局异常处理

在 .netcore中可以自定义自己的异常类型,步骤如下:

1、自定义自己的异常类型UserOperationException 并继承自Exception

public class UserOperationException:Exception
    {
        public UserOperationException() { }

        public UserOperationException(string message) : base(message) { }

        public UserOperationException(string message, Exception innerException) : base(message, innerException) { }
    }

2、自定义自己的全局异常过滤器GlobalExceptionFilter 实现接口 IExceptionFilter

public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly IHostingEnvironment _env;
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(IHostingEnvironment env, ILogger<GlobalExceptionFilter> logger)
        {
            _env = env;
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            var json = new JsonErrorResponse
            {
                Message = context.Exception.Message
            };
            if (context.Exception.GetType() == typeof(UserOperationException))
            {
                
                context.Result = new BadRequestObjectResult(json);
            }else
            {
                json.Message = "zhengweiProject中发生了未知的内部异常!";
                if(_env.IsDevelopment())
                {
                    json.Message = context.Exception.StackTrace;
                }
                context.Result = new InternalServerErrorObjectResult(json);
            }
            _logger.LogError(context.Exception, context.Exception.Message);
            context.ExceptionHandled = true;
        }
    }

    public class InternalServerErrorObjectResult:ObjectResult
    {
        public InternalServerErrorObjectResult(object error):base(error)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }

3、在项目中使用,第一篇文章已说过,项目使用微服务webapi架构。新建控制器UserController.cs 在get方法中抛出异常,

在获取UserIdentity值时故意获取了数据库中没有的值

[Route("api/users")]
    public class UserController : BaseController
    {
        public UserContext _userContext;
        public UserController(UserContext userContext)
        {
            _userContext = userContext;
        }
        // GET api/values
        [Route("")]
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var user =_userContext.Users.SingleOrDefault(u=>u.Id == UserIdentity.UserId);
            if(user == null)
            {
                throw new UserOperationException("获取用户数据出错,用户ID:"+UserIdentity.UserId);

            }
            return Json(user);
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [Route("")]
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [Route("")]
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

4、运行项目后,postman访问API,结果如下:

 

posted @ 2020-05-03 15:22  爱生活,爱代码  阅读(601)  评论(0编辑  收藏  举报