我有一个用于每个异常的全局异常处理程序,我希望它处理不同的 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);
}
最佳答案
我找到了解决问题的方法。
所以我用@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/