【发布时间】:2017-11-28 01:04:49
【问题描述】:
我正在使用 Spring Boot 1.5.4 和 Spring JPA、Spring Data REST、HATEOAS... 我正在寻找一种最佳实践(Spring 方式)来自定义异常 Spring Data REST 正在管理添加 i18n 支持。
我将 MessageException (https://github.com/spring-projects/spring-data-rest/blob/master/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/support/ExceptionMessage.java) 类作为起点。
一个典型的 Spring Data REST 异常非常好:
{
"timestamp": "2017-06-24T16:08:54.107+0000",
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint",
"path": "/api/v1/workSessions/start"
}
我想做的是:
- 本地化错误和消息字段 (i18n)
- 可能将消息文本更改为其他内容(始终本地化)
我在 Spring Data REST 文档中没有找到关于如何自定义或本地化异常 (https://docs.spring.io/spring-data/rest/docs/current/reference/html/) 的任何参考。 我希望有一种优雅的方式来做到这一点。
我在我的 WebMvcConfigurerAdapter 中添加了这个:
@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
public class SmartLocaleResolver extends CookieLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) {
return super.determineDefaultLocale(request);
}
return request.getLocale();
}
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasenames("i18n/messages"); // name of the resource bundle
source.setUseCodeAsDefaultMessage(true);
return source;
}
我想我可以通过这种方式拦截异常:
@ControllerAdvice(annotations = RepositoryRestController.class)
public class GenericExceptionHandler {
@ExceptionHandler
public ResponseEntity handle(Exception e, Locale locale) {
//missing part...
return new ResponseEntity(exceptionMessageObject, new HttpHeaders(), httpStatus);
}
有没有办法使用 Spring 最佳实践将所有内容组合在一起?
【问题讨论】:
标签: java spring spring-mvc spring-data-rest