feat(i18n): 新增多语言国际化支持

引入 II18nService 与 I18nServiceImpl,使 AppleService 及全局异常处理器可按 Accept-Language 返回本地化错误信息;ErrorCode 新增 getCodeAsString;数据库连接改为 keyborad_db。
This commit is contained in:
2025-12-01 21:54:51 +08:00
parent 683accca83
commit bcbb623ee4
9 changed files with 261 additions and 45 deletions

View File

@@ -3,6 +3,8 @@ package com.yolo.keyborad.exception;
import com.yolo.keyborad.common.BaseResponse;
import com.yolo.keyborad.common.ErrorCode;
import com.yolo.keyborad.common.ResultUtils;
import com.yolo.keyborad.service.II18nService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -16,15 +18,45 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
public class GlobalExceptionHandler {
private final II18nService i18nService;
public GlobalExceptionHandler(II18nService i18nService) {
this.i18nService = i18nService;
}
@ExceptionHandler(BusinessException.class)
public BaseResponse<?> businessExceptionHandler(BusinessException e) {
public BaseResponse<?> businessExceptionHandler(BusinessException e, HttpServletRequest request) {
log.error("businessException: " + e.getMessage(), e);
return ResultUtils.error(e.getCode(), e.getMessage());
// 获取请求头中的Accept-Language
String acceptLanguage = request.getHeader("Accept-Language");
// 根据错误码获取国际化消息
String errorMessage = i18nService.getMessageWithAcceptLanguage(String.valueOf(e.getCode()), acceptLanguage);
// 如果没有找到国际化消息,使用原始消息
if (errorMessage == null) {
errorMessage = e.getMessage();
}
return ResultUtils.error(e.getCode(), errorMessage);
}
@ExceptionHandler(RuntimeException.class)
public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
public BaseResponse<?> runtimeExceptionHandler(RuntimeException e, HttpServletRequest request) {
log.error("runtimeException", e);
return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
// 获取请求头中的Accept-Language
String acceptLanguage = request.getHeader("Accept-Language");
// 根据错误码获取国际化消息
String errorMessage = i18nService.getMessageWithAcceptLanguage(String.valueOf(ErrorCode.SYSTEM_ERROR.getCode()), acceptLanguage);
// 如果没有找到国际化消息,使用原始消息
if (errorMessage == null) {
errorMessage = e.getMessage();
}
return ResultUtils.error(ErrorCode.SYSTEM_ERROR.getCode(), errorMessage);
}
}
}