@ExceptionHandler只能使用Exception.class

时间:2012-04-06 13:48:18

标签: java spring spring-mvc

我在我的一个控制器上使用@ExceptionHandler注释,但如果我使用Exception.class以外的任何异常类型,页面将返回消息

  

客户端发送的请求在语法上是不正确的。

这是我的控制器:

@Controller
@RequestMapping("/foobar")
public class TodayInHistoryController {

@Autowired(required = true)
private TodayInHistoryService service;

private static final String DATE_FMT = "yyyyMMdd";

/**
 * 
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public HistoryContent getTodayInHistory(
    @RequestParam(value = "date", required = false) Date date) {
if (date != null)
    return service.getHistoryContent(date);

return service.getHistoryContent();
}

/**
 * Binds URL arguments to their correct object representation.
 * 
 * @param binder
 */
@InitBinder
public void initBinder(WebDataBinder binder) {
// Date object binder
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FMT);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
    dateFormat, false));
}

/**
 * 
 * @return
 */

// If I change the value param of the annotation to Exception.class it works fine...
@ExceptionHandler(NumberFormatException.class)
public ModelAndView handleParseException(Exception ex) {
    // create and populate Map to hold error data
Map<String, String> errorData = new HashMap<String, String>();
errorData.put("errorMessage","Formatting error occurred");
errorData.put("errorDetails", "None");

// create and return ModelAndView
ModelAndView mv = new ModelAndView();
mv.addAllObjects(errorData);

    return mv;
}
}

这是我的春季配置(相关内容)

@Configuration
@Import(ServicesConfig.class)
@ImportResource({ "classpath:applicationContext-security.xml",
"classpath:dataSources.xml" })
@EnableWebMvc
@ComponentScan(basePackages = "my.controller")
public class WebConfig {

@Bean
public ViewResolver contentNegotiatingViewResolver() {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setIgnoreAcceptHeader(true);
resolver.setDefaultContentType(MediaType.APPLICATION_JSON);
resolver.setFavorPathExtension(true);
resolver.setOrder(1);

// setup mediaTypes
Map<String, String> mediaTypes = new HashMap<String, String>();
mediaTypes.put("json", "application/json");
mediaTypes.put("xml", "application/xml");
resolver.setMediaTypes(mediaTypes);

// setup defaultViews
List<View> defaultViews = new ArrayList<View>();
defaultViews.add(jsonView());
defaultViews.add(xmlView());
resolver.setDefaultViews(defaultViews);

return resolver;
}

@Bean
public View jsonView() {
return new MappingJacksonJsonView();
}

@Bean
public View xmlView() {
return new MarshallingView(new CastorMarshaller());
}
}

1 个答案:

答案 0 :(得分:2)

这里的问题是spring尝试将日期字符串转换为Date并失败。如果发生这种情况TypeMismatchException(包裹IllegalArgumentException,其又包裹ParseException)被抛出,您应该处理它而不是NumberFormatException

当您将异常类更改为Exception时,它已被处理,TypeMismatchException扩展Exception

提示:如果您正在使用任何日志记录框架,请尝试为spring mvc类启用调试日志记录,它可以清除很多内容。

例如,在你的lo4j.propeties中添加这样的东西:

log4j.logger.org.springframework.servlet=DEBUG