MyBatis:Catch消息从SQL Server抛出存储过程

时间:2017-05-04 09:40:43

标签: sql-server spring stored-procedures mybatis

我正在使用Spring,MyBatis和Microsoft SQL Server。在我的项目中,我需要从MyBatis mapper xml 文件中调用一个过程。

所以,我这样做了:

<select id="callProcedure" parameterType="TestBean" statementType="CALLABLE" >
    {CALL callprocedure(#{id},#{regId})}
</select>

而且,这很有效。之后,我在我的存储过程中添加了 THROW 语句,如下所示:

THROW 50002, "Invalid Parameters", 1;

而且,我在我的DAO java类中捕获异常,如下所示:

try {
    myMapper.callProcedure(testBean);
} catch (Exception e) {
    System.out.println(e.getMessage());
}

那,主要问题在这里。打印出消息时,它显示了很多行和原因。不仅仅是我抛出的信息。我只想要我抛出的信息。

我无法通过调用e.getMessage()来获取我从该过程中抛出的消息。

这显示以下消息:

org.springframework.jdbc.UncategorizedSQLException: 
### Error querying database.  Cause:com.microsoft.sqlserver.jdbc.SQLServerException: Invalid Parameters
### The error may exist in mybatis/mapper/application/test.xml
### The error may involve com.test.core.mapper.application.TestMapper.callProcedure-Inline
### The error occurred while setting parameters
### SQL: {CALL callprocedure(?,?)}
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid Parameters; uncategorized SQLException for SQL []; SQL state [S0001]; error code [50002]; Invalid Parameters; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Invalid Parameters
...

我很难从程序中获取抛出消息。我该如何解决这个问题?

或者是其他任何工作方式?求你帮帮我。

感谢。

1 个答案:

答案 0 :(得分:0)

在这里,我得到了答案。当我尝试如下时,我得到了我的信息。

try {
    myMapper.callProcedure(testBean);
} catch (Exception e) {
    System.out.println(e.getCause().getMessage());
}

这解决了我的问题。