springboot2 全局异常处理

631 阅读1分钟
@GetMapping("exp/u/{id}")
	public UserInfo getUserInfoById(@PathVariable(name="id") String userId ) {
		System.out.println(String.format("输入的参数:%s", userId));
		int i=1/0;
		return new UserInfo("张三", "成都");
	}
@RestControllerAdvice
public class CustomExceptionHandler {
	
	public static final Logger logger=LoggerFactory.getLogger(CustomExceptionHandler.class);
	
	/**
	 * Exception 需要处理的异常
	 * @Description
	 * @author hedong
	 * @date 2018年12月13日 下午11:00:55
	 * @modifyNote 
	 * @param ex
	 * @param request
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	Object handException(Exception ex,HttpServletRequest request) {
		
		logger.error("请求url:{}, 异常消息信息: {} ", request.getRequestURI(),ex.getMessage());
		logger.error("详细异常信息:", ex);
		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("code", 100);
		map.put("msg", "发生异常");
		map.put("url",request.getRequestURI());
		return map;
	}

}