在springboot中catch SQLException不到,是因爲springboot包裝了所有DB的異常,使用DataAccessException。
今天浪費我一個小時查這個小東西╭(╯^╰)╮
在下面的source中,不在springboot環境時,catch SQLException,在這就一直提示remove。
因爲springboot又給包裝了一層DB異常類型,驚不驚喜意不意外。
所以只能老老實實catch DataAccessException,(SQLException)e.getCause()強轉類型,可以取SQLState。
try{
idValueLong = comReceptNumSeqMapper.selectReceptNumSeq(tableName);
} catch (DataAccessException e) {
SQLException se = (SQLException)e.getCause();
String sqlstate = se.getSQLState();
if(UtilConst.STR_SQLSTATE_SEQUENCE_OVERFLOW.equals(sqlstate)) {
// 採番結果値が採番最大値を超えた場合
String messagestr = msgSrc.getMessage(MessageId.EG000052, new String[] {numericTyp, subcode}, Locale.JAPAN);
log.error(messagestr);
throw new Exception(messagestr);
}else {
throw new Exception(e.getMessage());
}
}
下面這段是DataAccessException的註解,說的也是它就是一個大包工頭,哪個DB異常都是他小弟,有事只能先找大哥談。
* <p>This exception hierarchy aims to let user code find and handle the
* kind of error encountered without knowing the details of the particular
* data access API in use (e.g. JDBC). Thus it is possible to react to an
* optimistic locking failure without knowing that JDBC is being used.
*
* <p>As this class is a runtime exception, there is no need for user code
* to catch it or subclasses if any error is to be considered fatal
* (the usual case).