java – 使用Spring Data REST处理自定义异常(i18n)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 使用Spring Data REST处理自定义异常(i18n),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5187字,纯文字阅读大概需要8分钟。
内容图文
![java – 使用Spring Data REST处理自定义异常(i18n)](/upload/InfoBanner/zyjiaocheng/789/6666c4386089476f9447c0bb04a049cd.jpg)
我正在使用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最佳实践将所有内容组合在一起?
解决方法:
@ControllerAdvice(annotations = RepositoryRestController.class)
public class GenericExceptionHandler {
@Autowired
private MessageSource messageSource;
@ExceptionHandler
//if you don't use Exception e in method you can remove it , live only Locale
public ResponseEntity handle(Exception e, Locale locale) {
String errorMessage = messageSource.getMessage(
"error.message", new Object[]{},locale);
//set message or return it instead of exceptionMessageObject
exceptionMessageObject.setMessage(exceptionMessageObject);
return new ResponseEntity(exceptionMessageObject,
new HttpHeaders(), httpStatus);
}
见spring doc 7.15.1 Internationalization using MessageSource
” how I should create exceptionMessageObject to be like the one Spring
Data REST creates? “
创建自己的错误包装器,如:
public class CustomError {
private HttpStatus status;
private String message;
private Exception originalException;//if you need it
// getter setter
}
“How to have different messages for different exceptions? Should I
create a long if else chain checking the class of the exception? “
创建解析器,
private String resolveExceptionToMessage(Exception exceptio){
//or put in map<Exceptio,String error.message.type1>
// String errorCode = map.get(excptio);
//eturn messageSource.getMessage(errorCode , new Object[]{},locale);
if(exceptio instanceof ....){
return messageSource.getMessage("error.message.type1", new Object[]{},locale);
}
return "";
}
或者使用带有@ExceptionHandler({CustomException1.class}),@ ExceptionHandler({CustomException1.class})的方法….并且在每个方法中放入errror.code,所有其他部分都是相似的
@ExceptionHandler({ CustomException1.class})
public ResponseEntity handleException1() {
return createError(code for this exceptio 1);
}
@ExceptionHandler({ CustomException2.class})
public ResponseEntity handleException2() {
return createError(code for this exceptio 2);
}
private ResponseEntity createError(String errorCode ) {
CustomError customError = new CustomError();
customError.setHttpStatus(HttpStatus.BAD_REQUEST);
String errorMessage = messageSource.getMessage(
errorCode , new Object[]{},locale);
customError.setMessage(errorMessage );
customError.setOriginalException(e);
return new ResponseEntity<Object>(customError, new HttpHeaders(),
customError.getStatus());
}
How set httpStatus? I would like use the default status Spring Data
REST use for commons exceptions…
public ResponseEntity handle(Exception e, Locale locale) {
CustomError customError = new CustomError();
customError.setHttpStatus(HttpStatus.BAD_REQUEST);
customError.setMessage(resolveExceptionToMessage(e));
customError.setOriginalException(e);
return new ResponseEntity<Object>(customError, new HttpHeaders(),
customError.getStatus());
}
内容总结
以上是互联网集市为您收集整理的java – 使用Spring Data REST处理自定义异常(i18n)全部内容,希望文章能够帮你解决java – 使用Spring Data REST处理自定义异常(i18n)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。