赞
踩
没有添加全局异常处理时,当Controller的方法直接抛出异常时,openfeign会收到500错误,导致无法进行正常的处理。通过定义全局异常处理,将异常情况,通过预定义的错误码进行返回,以便调用端能够正常处理。
1. 定义全局异常类
- package com.demo.handler;
-
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.FieldError;
- import org.springframework.web.bind.MethodArgumentNotValidException;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * author:
- */
- @ControllerAdvice
- public class GlobalExceptionHandler {
- private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
-
-
- @ExceptionHandler(RuntimeException.class)
- @ResponseBody
- public AjaxResult handleException(Exception e, HttpServletRequest request) {
- logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
- return AjaxResult.error(e.getMessage());
- }
-
- // @ExceptionHandler(BusinessException.class)
- // @ResponseBody
- // public Result handleException(BusinessException e, HttpServletRequest request) {
- // logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
- // return ResultUtils.error(e.getCode(),e.getMessage());
- // }
- }

2. 添加该类后,如果@ControllerAdvice不生效,需要确保能够扫描到,也就是需要放在启动类所在包之下。或者添加扫描路径,比如:
@SpringBootApplication(scanBasePackages = {"com.xxx"})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。