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);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章