json - 如何在 Spring 全局异常处理程序中处理 JSON 方法中的不同异常?

标签 json spring error-handling

我有一个用于每个异常的全局异常处理程序,我希望它处理不同的 JSON 方法。但我想保持中心化。

@ControllerAdvice
public class GlobalExceptionHandler extends AbstractHandlerExceptionResolver{

    @ExceptionHandler(Exception.class)
    @Override
    protected ModelAndView doResolveException(HttpServletRequest  request, 
                                              HttpServletResponse response,
                                              Object handler, 
                                              Exception ex) {

   // Omitted code like logging, message translation, etc.

    String contentType = response.getContentType();

    //FIXME: This do NOT WORK. contentType will be null
    if(contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)){

            // Add error as a header                                
            modelAndView.setView( new MappingJackson2JsonView() );
    }else{
            // Add error to model   
            modelAndView.setViewName(MyJSPView);                        
    }
}

调试后,我看到内容类型为空,我不能使用它。 我如何区分这两个电话? .为了测试,我编写了这对方法:
@RequestMapping(value = "jspTest")
public String jspTest(){
    throw new UserMessageException(ErrorMessages.TESTING_ERROR);
}


@RequestMapping(value = "jsonTest", produces = ContentType.JSON)
@ResponseBody
public String jsonTest(){
    throw new UserMessageException(ErrorMessages.TESTING_ERROR);
}

最佳答案

我找到了解决问题的方法。

  • 我错误地将@ControllerAdvice 和@ExceptionHandler 混合在AbstractHandlerExceptionResolver 中。它们是处理异常的不同方法。见 this link
    所以我用@Component 替换了@ControllerAdvice 并删除了@ExceptionHandler。现在方法处理程序在处理程序参数中返回
  • 我使用了这种方法:

  • 私有(private)静态 bool isJson(对象处理程序){
    if( ! (handler instanceof HandlerMethod)){
        return false;
    }
            
    RequestMapping mapping =  ((HandlerMethod) handler).getMethodAnnotation(RequestMapping.class);
    
    for(String mimeType : mapping.produces()){
        if( mimeType.indexOf(MediaType.APPLICATION_JSON_VALUE)  != -1 ){
            return true;
        }
    }
    
    // Mime types produced does not include  application/json
    return false;
    
    }

    关于json - 如何在 Spring 全局异常处理程序中处理 JSON 方法中的不同异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27688147/

    相关文章:

    java - 为什么我的 Spring webflux 应用程序在每个请求上都会生成临时文件?

    spring - 使用 Spring Security 以根据用户是否经过身份验证为同一 URL 显示不同的内容

    android - 如果 webview 中没有可用的 favicon,则显示 favicon-default.png

    php - Mysqli PHP我希望未知服务器主机时出现自定义错误消息

    java - JSONPath和Traverson过滤: single element array

    javascript - 如何使用坐标数组在谷歌地图 API 中绘制多边形?

    java - IBM Integration 总线,解析 json

    spring - 如何将列表从 Controller 传递给jsp?

    javascript - 使用 Async/Await 自定义错误处理

    javascript - 在本地存储中存储压缩的 json 数据