如何返回调用 jQuery AJAX 错误函数的错误消息和 HTTP 状态代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14488281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I return an error message and HTTP status code that calls jQuery AJAX error function?
提问by James
Using Spring, I have a SimpleMappingExceptionResolver that catches any unexpected exceptions in my application in the resolveException method. In the method, I return a ModelAndView that gives error message text back to the HTTP client. Here's the code:
使用 Spring,我有一个 SimpleMappingExceptionResolver 可以在我的应用程序中通过 resolveException 方法捕获任何意外异常。在该方法中,我返回一个 ModelAndView,它将错误消息文本返回给 HTTP 客户端。这是代码:
public class UnExpectedExceptionResolver extends SimpleMappingExceptionResolver {
private Log logger = LogFactory.getLog(this.getClass().getName());
private ResourceBundleMessageSource messageSource;
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
// let the end user know that an error occurred
Locale locale = RequestContextUtils.getLocale(request);
String messageText = messageSource.getMessage("systemError", null, locale);
Message message = new Message(messageText, MessageType.ERROR);
ModelAndView mav = new ModelAndView();
mav.setView(new MappingHymansonJsonView());
mav.addObject("message", message);
return mav;
}
As such, the response is returned with a HTTP status code of 200 with response text being the message (JSON). Unfortunately, the client thinks it's a valid response due to the 200 code and tries to process it as such. I tried setting the HTTP status code to 500 as follows:
因此,响应返回的 HTTP 状态代码为 200,响应文本为消息 (JSON)。不幸的是,由于 200 代码,客户端认为这是一个有效的响应,并尝试这样处理它。我尝试将 HTTP 状态代码设置为 500,如下所示:
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
right before the
就在
return mav;
statement. Unfortunately, this returns a HTML page indicating a internal error instead of my JSON message. How can I return the JSON message and still indicate a server error (or some type of error) to the client? Specifically, I expect the client's error function in the AJAX call to be invoked and still have the message data sent back to the client. FYI - I'm using jQuery on the client side.
陈述。不幸的是,这将返回一个指示内部错误的 HTML 页面,而不是我的 JSON 消息。如何返回 JSON 消息并仍然向客户端指示服务器错误(或某种类型的错误)?具体来说,我希望在 AJAX 调用中调用客户端的错误函数,并且仍然将消息数据发送回客户端。仅供参考 - 我在客户端使用 jQuery。
回答by shazinltc
I don't know how exactly you are making the requests to the server. But this is how I would do it.
我不知道你是如何向服务器发出请求的。但这就是我要做的。
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "your message")
public void handleException(IllegalStateException ex, HttpServletResponse response) throws IOException
{
}
In in the client side
在客户端
$.ajax({
type : "POST",
url : urlString,
data : params,
dataType : 'json',
success : function(data) {
// do something}
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status); //This will be 500
alert(xhr.responseText); // your message
//do stuff
}
回答by Boris Treukhov
In Spring 3.2 you can put your exception handler inside a @ControllerAdvice
annotated class.
在 Spring 3.2 中,您可以将异常处理程序放在带@ControllerAdvice
注释的类中。
Classes annotated with
@ControllerAdvice
can contain@ExceptionHandler
,@InitBinder
, and@ModelAttribute
methods and those will apply to@RequestMapping
methods across controller hierarchies as opposed to the controller hierarchy within which they are declared.@ControllerAdvice
is a component annotation allowing implementation classes to be auto-detected through classpath scanning.
用 注释的类
@ControllerAdvice
可以包含@ExceptionHandler
、@InitBinder
和@ModelAttribute
方法,这些将应用于@RequestMapping
跨控制器层次结构的方法,而不是在其中声明它们的控制器层次结构。@ControllerAdvice
是一个组件注释,允许通过类路径扫描自动检测实现类。
So if your controllers are picked up by autoscanning @Controller
annotated classes, @ControllerAdvice
should also work(if you scan @Controller
classes with an explicit annotation expression, you may need to register this bean separately).
因此,如果您的控制器是通过自动扫描带 @Controller
注释的类获取的,@ControllerAdvice
也应该可以工作(如果您@Controller
使用显式注释表达式扫描类,则可能需要单独注册此 bean)。
@ControllerAdvice
public class AppControllerAdvice{
@ExceptionHandler(Throwable.class)
ResponseEntity<String> customHandler(Exception ex) {
return new ResponseEntity<String>(
"Custom user message",
HttpStatus.INTERNAL_SERVER_ERROR);
}
Please note that the text is a part of the returned entity and notan HTTP reason phrase.
请注意,文本是返回实体的一部分,而不是HTTP 原因短语。
回答by ehrhardt
Here is how I did it.
这是我如何做到的。
public class CustomExceptionResolver extends AbstractHandlerExceptionResolver {
private static final Logger logger = Logger.getLogger(CustomExceptionResolver.class);
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
try {
response.reset();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/json");
MappingHymansonJsonView view = new MappingHymansonJsonView();
Map<String, String> asd = new HashMap<String, String>();
asd.put("message", ex.getMessage());
view.setAttributesMap(asd);
return new ModelAndView(view);
} catch (Exception e) {
logger.error("send back error status and message : " + ex.getMessage(), e);
}
return null;
}
And then of course in my json-servlet.xml file:
然后当然在我的 json-servlet.xml 文件中:
<bean id="exceptionResolver" class="com.autolytix.common.web.CustomExceptionResolver"/>
回答by Raghav
Add the following code to the frontcontrol
在前端控件中添加以下代码
@ExceptionHandler(Exception.class)
public @ResponseBody
MyErrorBean handleGeneralException(Exception e,
HttpServletRequest request, HttpServletResponse response) {
logger.info("Exception:" , e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
MyErrorBean errorBean = new MyErrorBean();
errorBean.setStatus(MyConstants.ERROR_STATUS);
return errorBean;
}`
Since you are using JSON I assume you will have a messageconverter configured in your code which will convert this to JSON. By setting the status and sending a bean you will be able to solve it.
由于您使用的是 JSON,我假设您将在代码中配置一个 messageconverter,它将把它转换为 JSON。通过设置状态并发送一个 bean,您将能够解决它。