程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用Spring Data REST处理自定义异常(i18n)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用Spring Data REST处理自定义异常(i18n)?

开发过程中遇到使用Spring Data REST处理自定义异常(i18n)的问题如何解决?下面主要结合日常开发的经验,给出你关于使用Spring Data REST处理自定义异常(i18n)的解决方法建议,希望对你解决使用Spring Data REST处理自定义异常(i18n)有所启发或帮助;
@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);
    }

参见Spring7.15.1使用messagesource进行国际化

创建您自己的错误包装器,例如:

public class CustomError {
    private httpStatus status;
    private String message;
    private Exception originalException;//if you need it        
    // getter setter
}

创建解析器

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

解决方法

我正在将Spring Boot 1.5.4与Spring JPA,Spring Data
REST,HATEOAS结合使用&Hellip;我正在寻找最佳实践(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"
}

我想做的是:

  1. 本地化错误和消息字段(i18n)
  2. 可能将消息文本更改为其他内容(始终本地化)

我没有在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最佳实践将所有内容放在一起?

大佬总结

以上是大佬教程为你收集整理的使用Spring Data REST处理自定义异常(i18n)全部内容,希望文章能够帮你解决使用Spring Data REST处理自定义异常(i18n)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。