java - @ExceptionHandler 仅适用于 Exception.class

标签 java spring spring-mvc

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

The request sent by the client was syntactically incorrect.

这是我的 Controller :

@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;
}
}

这是我的 spring 配置(相关的)

@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());
}
}

最佳答案

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

当您将异常类更改为 Exception 时,它会得到处理,因为 TypeMismatchException 扩展了 Exception

提示:如果您正在使用任何日志记录框架,请尝试为 spring mvc 类打开调试日志记录,它可以让事情变得更加清晰。

例如,在您的 lo4j.propeties 中添加类似的内容:

log4j.logger.org.springframework.servlet=DEBUG

关于java - @ExceptionHandler 仅适用于 Exception.class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10044397/

相关文章:

java - 动态更改 Spring bean 属性

java - 具有求和功能的 For 循环

java - Spring TCP 通过传入连接发送数据

jquery - 使用 Spring MVC 将 JSON 数组转换为 java List<String>

java - 出现错误 "getOutputStream() has already been called for this response"

java - Spring MVC PUT 方法我得到 HTTP 状态 405,无法重定向到另一个内部 View

java - 谷歌云平台 Java SDK 和 OSGI

spring - 如何在 Spring RestTemplate 中禁用 URL 编码?

java - Spring Boot 将 @Value 绑定(bind)到 Enum 不区分大小写

java - 使用 Spring WebClient 响应式读取行