在 Spring MVC 中抛出 CustomException 代替 ParseException

Throw CustomException in place of ParseException in Spring MVC

我正在尝试使用两种格式将字符串转换为日期。但是当 DateString 与这两种格式中的任何一种都不匹配时,它会抛出 ParseException。我在我的 ServiceImpl 中捕获了这个异常,一切都很好。但是现在,我想向用户展示一些关于格式不正确的消息。
问题: 我正在使用 ParseException 的 catch 块来抛出我的 customException,我知道这是一种不好的做法。我该怎么做才能避免这种情况。

ServiceImpl.java

try {
        CommonUtils.convertStringToDate(fooBean.getDateString());
    } catch (ParseException e) {
        throw new DateParseException("Problems with your date.");
    }

GlobalExceptionHandler.java

@ExceptionHandler(DateParseException.class)
public String handleParseException(HttpServletRequest request, Exception ex, String msg){
    logger.error("DateParseException Occured :: "+ex.getMessage());
    ModelAndView model = new ModelAndView();
    model.addObject("message", msg);
    return "error";
}

CommonUtils.java

public static Date convertStringToDate(String dateString) throws ParseException{
        DateFormat dateFormat1 = new SimpleDateFormat(Constants.USDATEFORMAT1);
        DateFormat dateFormat2 = new SimpleDateFormat(Constants.USDATEFORMAT2);
        DateFormat dateFormat3 = new SimpleDateFormat(Constants.USDATEFORMAT3);
        DateFormat dateFormat4 = new SimpleDateFormat(Constants.USDATEFORMAT4);
        boolean hyphenDelimeter = dateString.contains("-");
        boolean slashDelimeter = dateString.contains("/");
        int length = dateString.length();
        Date date = null;
        if(slashDelimeter){
            if(length == 10){
                    date = dateFormat1.parse(dateString);
            }else if(length == 8){
                    date = dateFormat2.parse(dateString);
            }
        }else if(hyphenDelimeter){
            if(length == 10){
                    date = dateFormat3.parse(dateString);
            }else if(length == 8){
                    date = dateFormat4.parse(dateString);
            }
        }
        return date;
    }

调整您的异常以包含 "cause exception" 异常并将捕获的异常包装在您的自定义异常中,如下所示:

...
} catch (final ParseException e) {
  throw new DateParseException("Problems with your date.", e);
}

或者向您抛出的异常添加更相关的错误消息:

...
} catch (final ParseException e) {
  throw new DateParseException("Date could not be parsed.");
}

我会做前者以保留堆栈跟踪,这样您就可以更详细地了解哪里出了问题。