[英]How to handle custom exceptions using i18 message
我编写了一个带有自定义异常的 spring 引导应用程序。 一切运作良好。 但是,我对本地化还很陌生。 我喜欢为 Postman 标头添加德语; 从-->“你没有做任何事情来拥有飞机”到-->“Sie haben nichts getan, um ein Flugzeug zu haben”,我的工作代码如下;
My customException below;
public class PlaneTypeNotFoundException extends RuntimeException {
private static final long serialVersionUID = 4314211343358454345L;
public PlaneTypeNotFoundException () {
super("You did not do anything to have a plane");
}
}
我的异常响应如下;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponse {
private LocalDateTime date;
private String message;
}
我的异常处理程序 Class 下面;
@ControllerAdvice
@RestController
@Slf4j
public class PlaneTypeExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(PlaneTypeNotFoundException.class)
public final ResponseEntity<Object> handlePlaneTypeNotFoundException(PlaneTypeNotFoundException ex,
WebRequest request) {
log.debug("PlaneType Not Found --> {}", ex.getMessage(), request);
ExceptionResponse exceptionResponse = new ExceptionResponse(LocalDateTime.now(), ex.getMessage());
return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
}
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
log.debug("The request Parameteres whic you are sending is wrong", ex.getMessage(), request);
Map<String, Object> body = new LinkedHashMap<>();
body.put("date", LocalDate.now());
body.put("status", status.value());
List<String> errors = ex.getBindingResult().getFieldErrors().stream().map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
我的 LocaleResolver class 下面;
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");
source.setUseCodeAsDefaultMessage(true);
return source;
}
@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
}
此外,在资源中,我创建了一个名为“i18n”的文件夹,此外,还创建了两个名为“messages_en.properties”、“messages.de”的文件。 但是,我不知道我必须在这个文件中写什么。 是不是有点像.. plane.type.not.found = 你没有做任何事情来拥有一架飞机,以及如何将我的语言环境自定义解析器传递给 Controlleradvice,它是 PlaneTypeExceptionHandler 以便能够将 postman 调用从英语转换为德语。
您必须将消息作为键值对写入属性中。
plane_msg = "你没有做任何事情来拥有一架飞机"
plane_msg = "Sie haben nichts getan, um ein Flugzeug zu habe"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.