// 请求处理方法 ... // 异常处理方法 // 定制一个已有异常的HTTP状态码 @ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation") // 409 @ExceptionHandler(DataIntegrityViolationException.class) publicvoidconflict(){ // 啥也不干 } // 指定view来渲染对应的异常 @ExceptionHandler({SQLException.class,DataAccessException.class}) public String databaseError(){ // Nothing to do. Returns the logical view name of an error page, passed // to the view-resolver(s) in usual way. // Note that the exception is NOT available to this view (it is not added // to the model) but see "Extending ExceptionHandlerExceptionResolver" // below. // 啥也不干,就返回异常页面view的名称 // 注意这里的view访问不到异常,因为异常没有添加到model中 return"databaseError"; }
注意,使用@ExceptionHandler一定要指定处理的是哪个异常,否则会报异常:java.lang.IllegalArgumentException: No exception types mapped to {public java.lang.String XXController.exceptionHandler()}
<!-- See note below on how this interacts with Spring Boot --> <propertyname="defaultErrorView"value="error"/> <propertyname="exceptionAttribute"value="ex"/> <!-- Name of logger to use to log exceptions. Unset by default, so logging is disabled unless you set a value. --> <propertyname="warnLogCategory"value="example.MvcLogger"/> </bean>
@Configuration @EnableWebMvc// Optionally setup Spring MVC defaults (if you aren't using // Spring Boot & haven't specified @EnableWebMvc elsewhere) publicclassMvcConfigurationextendsWebMvcConfigurerAdapter{ @Bean(name="simpleMappingExceptionResolver") public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() { SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties(); mappings.setProperty("DatabaseException", "databaseError"); mappings.setProperty("InvalidCreditCardException", "creditCardError");
r.setExceptionMappings(mappings); // None by default r.setDefaultErrorView("error"); // No default r.setExceptionAttribute("ex"); // Default is "exception" r.setWarnLogCategory("example.MvcLogger"); // No default return r; } ... }
这里最有用的可能就是defaultErrorView了,他可以用于定制默认的错误页面。
自己继承SimpleMappingExceptionResolver来扩展功能也是非常常见的
继承类可以在构造函数中设置好默认配置
覆盖buildLogMessage方法来自定义日志信息,默认返回固定的:Handler execution resulted in exception