【问题标题】:Spring boot - i18n error messagesSpring Boot - i18n 错误消息
【发布时间】:2018-07-31 18:58:34
【问题描述】:

当使用带有简单 rest api 的 Spring boot 时,由于某种原因我得到一个错误,它是英文的,像这样:

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '2018-07-35'; nested exception is org.joda.time.IllegalFieldValueException: Cannot parse \"2018-07-35\": Value 35 for dayOfMonth must be in the range [1,31]" 

是否可以根据请求语言环境翻译所有这些 Spring Boot 消息?

【问题讨论】:

  • i18n 与将字符串转换为日期有什么关系?无论如何,没有一个月有 35 天。
  • 请在询问之前阅读错误原因
  • 问题不在于邮件内容。问题是关于错误消息的国际化。

标签: java spring spring-boot internationalization


【解决方案1】:

在春季,错误日志的重要部分通常位于消息的末尾:

Value 35 for dayOfMonth must be in the range [1,31]"

您是否想延长几个月?

抱歉,我没有完全阅读您的问题。

您无法在本地翻译堆栈跟踪,这意味着您需要了解本机和库函数的所有可能消息,然后创建一些翻译文件。

但是使用 try 和 catch 可以捕获一些异常并打印自定义消息:

 public void parseDate(String string){
        try{
            Date date = Date.parse(string);
        }catch(IllegalFieldValueException e){
            System.err.println("Date " + string + "is invalid in your local");
        }
    }

我这里用随意调用做一个简单的例子。

但 spring 并不总是你能做到这一点,所以 GlobalExceptionHandler 是你的朋友,这里是我项目代码中的一个例子:

@ControllerAdvice
public class GlobalExceptionHandlerController {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandlerController.class);

    @ExceptionHandler(UsernameNotFoundException.class)
    public @ResponseBody
    ResponseEntity usernameNotFound(UsernameNotFoundException e) {
        log.info(e.getMessage());
        return new ErrorResponseEntity(HttpStatus.FORBIDDEN, e);
    }

    @ExceptionHandler(AuthenticationException.class)
    public @ResponseBody
    ResponseEntity wrongAuthentication(AuthenticationException e) {
        log.info(e.getMessage());
        return new ErrorResponseEntity(HttpStatus.FORBIDDEN, e);
    }
}

【讨论】:

  • 我希望 Spring Boot 有某种语言环境配置,可以翻译大部分消息。
  • 不,Spring 也使用外部库,例如您的错误消息是由与 Spring Boot 无关的 'org.joda.time.IllegalFieldValueException' 生成的
猜你喜欢
  • 2016-03-27
  • 2012-10-13
  • 1970-01-01
  • 2017-12-28
  • 2018-09-07
  • 2019-08-26
  • 2011-08-17
  • 1970-01-01
  • 2021-07-16
相关资源
最近更新 更多