统一异常处理

利用@ControllerAdvice 注解来捕获控制器抛出的异常

import com.educationtek.common.domain.vo.ResultVo;
import com.educationtek.common.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
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;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultVo jsonErrorHandlerException(HttpServletRequest req, Exception e) {
log.error("调用url:{}, 报错信息:{}",req.getRequestURL().toString(),e.getMessage());
e.printStackTrace();

if (e instanceof MarkingException) {
MarkingException exception = (MarkingException) e;
return ResultUtils.error(exception.getCode(), exception.getMessage());
} else if (e instanceof BaseException) {
BaseException exception = (BaseException) e;
return ResultUtils.error(exception.getCode(), exception.getMessage());
} else {
return ResultUtils.error(-1, e.getMessage());
}
}
}

把这个类放在Common包下的exception包下,后面在每个模块下的主程序Application类使用@ComponentScan注解引入进来,第一个参数是GlobalExceptionHandler所在的包名,第二个参数为Application所在的包名

@ComponentScan(basePackages = {"com.educationtek.common.exception", "com.educationtek.hystrix"})
posted @ 2018-09-25 15:47  looyee  阅读(122)  评论(0编辑  收藏  举报