spring boot 的异常统一处理

spring boot 的异常统一处理

/**
 * 全局的异常处理
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 默认的异常处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ResData defaultExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
    	Map<String, String> requestParam = getRequestParam(req);
    	String ip = WechatCommonParamUtil.getLocalIP(req);
        logger.error("defaultExceptionHandler ip:{}, url:{}, requestParam:{}, error:{}", ip, req.getRequestURI(), requestParam, e);
        return ResData.fail(ExceptionCode.SERVER_EXCEPTION,"访问太火爆,服务器开小差了!");
    }
    
    /**
     * 获取请求参数
     * @param req
     * @return
     */
    private Map<String, String> getRequestParam(HttpServletRequest req) {
    	Enumeration<String> parameterNames = req.getParameterNames();
    	Map<String, String> paramMap = new HashMap<>();
    	while (parameterNames.hasMoreElements()) {
    		String name = (String) parameterNames.nextElement(); //参数名称
    	    String value = req.getParameter(name); //根据参数名称获取到参数值
    	    paramMap.put(name, value);
		}
    	return paramMap;
    }
    
    /**
     * 绑定异常的处理(非json格式的参数校验处理)
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = BindException.class)
    public ResData bindExceptionHandler(HttpServletRequest req, BindException e) throws Exception {
    	String message = e.getFieldErrors()
    					  .stream()
    					  .findFirst()
    					  .get()
    					  .getDefaultMessage();
    	Map<String, String> requestParam = getRequestParam(req);
    	String ip = WechatCommonParamUtil.getLocalIP(req);
    	logger.error("bindExceptionHandler ip:{}, url:{}, requestParam:{}, errorMessage:{}", ip, req.getRequestURI(), requestParam, message);
    	return ResData.fail(ExceptionCode.BIND_EXCEPTION,message);
    }
    
    /**
     * 约束校验异常的处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResData constraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException e) throws Exception {
    	String message = e.getMessage();
    	if (message.contains(":")) {
    		message = message.split(":")[1].trim();
    	}
    	if(message.contains(",")) {
    		message = message.substring(0, message.lastIndexOf(","));
    	}
    	Map<String, String> requestParam = getRequestParam(req);
    	String ip = WechatCommonParamUtil.getLocalIP(req);
    	logger.error("constraintViolationExceptionHandler ip:{}, url:{}, requestParam:{}, errorMessage:{}", ip, req.getRequestURI(), requestParam, message);
    	return ResData.fail(ExceptionCode.CONSTRAINT_VIOLATION_EXCEPTION,message);
    }
    
    /**
     * 业务层异常处理
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = ServiceException.class)
    public ResData serviceExceptionHandler(HttpServletRequest req, ServiceException e) throws Exception {
    	String message = e.getMessage();
    	int errorCode = e.getErrorCode();
    	Map<String, String> requestParam = getRequestParam(req);
    	String ip = WechatCommonParamUtil.getLocalIP(req);
    	logger.error("serviceExceptionHandler ip:{}, url:{}, requestParam:{}, errorCode:{}, errorMessage:{}", ip, req.getRequestURI(), requestParam, errorCode, message);
    	return ResData.fail(errorCode,message);
    }
    
    /**
     * 方法参数没有传入的异常处理(json格式参数校验处理)
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResData methodArgumentNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) throws Exception {
    	String message = e.getBindingResult()
    					  .getFieldErrors()
    					  .stream()
    					  .findFirst()
    					  .get()
    					  .getDefaultMessage();
    	Map<String, String> requestParam = getRequestParam(req);
    	String ip = WechatCommonParamUtil.getLocalIP(req);
    	logger.error("methodArgumentNotValidExceptionHandler ip:{}, url:{}, requestParam:{}, errorMessage:{}", ip, req.getRequestURI(), requestParam, message);
    	return ResData.fail(ExceptionCode.METHOD_ARGUMENT_EXCEPTION,message);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章