Spring MVC-基于Accept标头的@ExceptionHandler

Sot*_*lis 5 java spring spring-mvc

我有一个HandlerInterceptorAdapter拦截所有请求并执行用户授权检查的工具。非常基本的:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    User user = ... // get user
    checkIfAuthorized(user); // throws AuthorizationException
    return true;
}
Run Code Online (Sandbox Code Playgroud)

然后,我有一个@ExceptionHandlerAuthorizationException

@ExceptionHandler(value = AuthorizationException.class) 
public ResponseEntity<String> handleNotAuthorized(AuthorizationException e) {
    // TODO Custom EXCEPTION HANDLER for json/jsp/xml/other types, based on content type
    ResponseEntity<String> responseEntity = new ResponseEntity<>("You are not authorized to access that page.", HttpStatus.UNAUTHORIZED);
    return responseEntity;
}
Run Code Online (Sandbox Code Playgroud)

如果(未经授权)请求接受text/plain(可以很容易地更改为json),这很好。如何@ExceptionHandler为特定Accept标题设置不同的?

@RequestMappingproduces()。有类似的东西@ExceptionHandler吗?

Luc*_*ano 2

我想到两种方法:

手动

public ResponseEntity<String> handleNotAuthorized(AuthorizationException e, HttpServletRequest request) {
    // TODO Custom EXCEPTION HANDLER for json/jsp/xml/other types, based on content type
    if (/*read header accept from request and build appropiate response*/) {}
    ResponseEntity<String> responseEntity = new ResponseEntity<>("You are not authorized to access that page.", HttpStatus.UNAUTHORIZED);
    return responseEntity;
Run Code Online (Sandbox Code Playgroud)

自动地

@ResponseBody
public SomeObject handleNotAuthorized(AuthorizationException e, HttpServletRequest request) {
    // TODO Custom EXCEPTION HANDLER for json/jsp/xml/other types, based on content type
    /* Construct someObject and let Spring MessageConverters transform it to JSON or XML. I don't remember what happens in case of HTML (it should go to a view)*/
    return someObject;
Run Code Online (Sandbox Code Playgroud)

不要忘记设置响应的状态代码。