当前位置:   article > 正文

通过全局异常处理返回openfeign接口调用结果_openfegion怎么进行统一异常处理

openfegion怎么进行统一异常处理

没有添加全局异常处理时,当Controller的方法直接抛出异常时,openfeign会收到500错误,导致无法进行正常的处理。通过定义全局异常处理,将异常情况,通过预定义的错误码进行返回,以便调用端能够正常处理。

1. 定义全局异常类

  1. package com.demo.handler;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.validation.BindingResult;
  5. import org.springframework.validation.FieldError;
  6. import org.springframework.web.bind.MethodArgumentNotValidException;
  7. import org.springframework.web.bind.annotation.ControllerAdvice;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import javax.servlet.http.HttpServletRequest;
  11. /**
  12. * author:
  13. */
  14. @ControllerAdvice
  15. public class GlobalExceptionHandler {
  16. private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  17. @ExceptionHandler(RuntimeException.class)
  18. @ResponseBody
  19. public AjaxResult handleException(Exception e, HttpServletRequest request) {
  20. logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
  21. return AjaxResult.error(e.getMessage());
  22. }
  23. // @ExceptionHandler(BusinessException.class)
  24. // @ResponseBody
  25. // public Result handleException(BusinessException e, HttpServletRequest request) {
  26. // logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
  27. // return ResultUtils.error(e.getCode(),e.getMessage());
  28. // }
  29. }

2. 添加该类后,如果@ControllerAdvice不生效,需要确保能够扫描到,也就是需要放在启动类所在包之下。或者添加扫描路径,比如:

@SpringBootApplication(scanBasePackages = {"com.xxx"})

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号