Jam*_*mes 4 ajax jquery spring exception http-status-codes
使用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 MappingJacksonJsonView());
mav.addObject("message", message);
return mav;
}
Run Code Online (Sandbox Code Playgroud)
因此,响应将返回HTTP状态代码200,响应文本为消息(JSON).不幸的是,客户认为这是一个有效的响应,因为200代码并试图处理它.我尝试将HTTP状态代码设置为500,如下所示:
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
Run Code Online (Sandbox Code Playgroud)
就在之前
return mav;
Run Code Online (Sandbox Code Playgroud)
声明.不幸的是,这会返回一个HTML页面,指示内部错误而不是我的JSON消息.如何返回JSON消息并仍向客户端指示服务器错误(或某种类型的错误)?具体来说,我希望调用AJAX调用中的客户端错误函数,并将消息数据发送回客户端.仅供参考 - 我在客户端使用jQuery.
sha*_*ltc 10
我不知道你是如何向服务器发出请求的.但这就是我要做的.
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "your message")
public void handleException(IllegalStateException ex, HttpServletResponse response) throws IOException
{
}
Run Code Online (Sandbox Code Playgroud)
在客户端
$.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
}
Run Code Online (Sandbox Code Playgroud)
在Spring 3.2中,您可以将异常处理程序放在带@ControllerAdvice注释的类中.
注释的类
@ControllerAdvice可以包含@ExceptionHandler,@InitBinder和@ModelAttribute方法,这些类将应用于@RequestMapping跨控制器层次结构的方法,而不是声明它们的控制器层次结构.@ControllerAdvice是一个组件注释,允许通过类路径扫描自动检测实现类.
因此,如果通过自动扫描带@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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,文本是返回实体的一部分,而不是 HTTP原因短语.
| 归档时间: |
|
| 查看次数: |
25797 次 |
| 最近记录: |