添加异常消息,以JSON响应 [英] Add exception message to json response
问题描述
我有一个code会抛出异常的具体类型是这样的:
I have a code which throws a specific type of exception like this:
throw new BadDataException("error message");
这几样的异常被抛出的方法,其数据类型是JSON里面。我有这样的这种异常类型的配置:
these kind of exceptions are thrown inside a method whose response type is json. I have a configuration for this exception type like this:
<global-exception-mappings>
<exception-mapping result="badDataError" exception="mypackage.BadDataException" />
</global-exception-mappings>
<result name="badDataError" type="json">
<param name="statusCode">500</param>
</result>
我想对异常信息添加到JSON响应展示给用户。有没有什么办法异常消息映射到响应时返回500状态code。 Ajax调用会是这样的:
I'd like to add the exception message to the json response to show it to the user. Is there any way to map the exception message to the response when a 500 status code is returned. The ajax call would be something like this:
$.ajax(
{
...
success: function(data, textStatus) {
alert('Success');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error");//I'd like to add here the reason (exception message)
}
...
}
);
我如何添加这个例外HTTP 500响应的自动消息? (如果有可能)
How can I add automatically the message of this exception to the HTTP 500 response? (if it is possible)
感谢
推荐答案
这是最后如何我已经做到了。我添加了一个的errorMessage场到HTTP 500响应这样的。
This is finally how I've done it. I've added a errorMessage field to the HTTP 500 response in this way.
<result name="badDataError" type="httpheader">
<param name="status">500</param>
<param name="headers.errorMessage">${exception.message}</param>
</result>
在Ajax请求我恢复的消息是这样的。
and in the ajax request I recover the message like this.
error: function (XMLHttpRequest, textStatus, errorThrown) {
var errorMessage = XMLHttpRequest.getResponseHeader('errorMessage');
....
}
也许有一个更优雅的方式来做到这一点,但至少它的工作原理。
Maybe there's a more elegant way to do this, but at least it works.
这篇关于添加异常消息,以JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!