如何针对HTML和JSON请求以不同方式处理Spring MVC中的异常 [英] How to handle exceptions in Spring MVC differently for HTML and JSON requests

查看:264
本文介绍了如何针对HTML和JSON请求以不同方式处理Spring MVC中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring 4.0.3中使用以下异常处理程序拦截异常并向用户显示自定义错误页面:

I'm using the following exception handler in Spring 4.0.3 to intercept exceptions and display a custom error page to the user:

@ControllerAdvice
public class ExceptionHandlerController
{
    @ExceptionHandler(value = Exception.class)
    public ModelAndView handleError(HttpServletRequest request, Exception e)
    {
        ModelAndView mav = new ModelAndView("/errors/500"));
        mav.addObject("exception", e);
        return mav;
    }
}

但现在我想要对JSON请求进行不同的处理,以便发生异常时,我会收到针对此类请求的JSON错误响应。目前上述代码也是由JSON请求触发的(使用 Accept:application / json 标头),JavaScript客户端不喜欢HTML响应。

But now I want a different handling for JSON requests so I get JSON error responses for this kind of requests when an exception occurred. Currently the above code is also triggered by JSON requests (Using an Accept: application/json header) and the JavaScript client doesn't like the HTML response.

如何针对HTML和JSON请求处理不同的异常?

How can I handle exceptions differently for HTML and JSON requests?

推荐答案

ControllerAdvice注释有一个名为basePackage的元素/属性,可以设置它来确定它应该为控制器扫描哪些包并应用建议。因此,您可以做的是将处理正常请求的控制器和处理AJAX请求的控制器分离到不同的包中,然后使用适当的ControllerAdvice注释编写2个异常处理控制器。例如:

The ControllerAdvice annotation has an element/attribute called basePackage which can be set to determine which packages it should scan for Controllers and apply the advices. So, what you can do is to separate those Controllers handling normal requests and those handling AJAX requests into different packages then write 2 Exception Handling Controllers with appropriate ControllerAdvice annotations. For example:

@ControllerAdvice("com.acme.webapp.ajaxcontrollers")
public class AjaxExceptionHandlingController {
...
@ControllerAdvice("com.acme.webapp.controllers")
public class ExceptionHandlingController {

这篇关于如何针对HTML和JSON请求以不同方式处理Spring MVC中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆