码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-05-03 16:46:23      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:get   ilo   str   全局   project   on()   inf   自己的   contex   

在 .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,结果如下:

技术图片

 

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

标签:get   ilo   str   全局   project   on()   inf   自己的   contex   

原文地址:https://www.cnblogs.com/zhengwei-cq/p/12822080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!