gpt4 book ai didi

java - Spring验证请求对象错误无法在@ControllerAdvice中找到消息

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:03 25 4
gpt4 key购买 nike

所有其他错误都通过 ControllerAdvice 正常工作,除了从后台 validator 抛出的错误之外, Controller 建议捕获异常,但无法从 @autowired 消息源找到消息。这是因为 validator 调用错误处理的方式吗?在 eclipse 中作为 Spring Boot 应用程序运行。 Spring Boot 版本 1.2.1.RELEASE。还使用 Spring Cloud 配置。

  @RestController
public class AutoController {
private static final Logger logger = LoggerFactory.getLogger(AutoController.class);

@Autowired
private AutoFacade autoFacade;

@RequestMapping(value = "/policies/policy/{policyNbr}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public AutoPolicy getPolicyDetails(@Valid GetPolicyDetails reqModelObj) {

AutoPolicy policyDetails = autoFacade.getPolicyDetails(reqModelObj.getPolicyNbr());

return policyDetails;
}
}

Controller 建议

@ControllerAdvice
public class RestExceptionProcessor {
private static final Logger logger = LoggerFactory.getLogger(RestExceptionProcessor.class);

@Autowired
private MessageSource messageSource;

@ExceptionHandler({APIServerErrorException.class})
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody

public APIStatus serverError(APIServerErrorException ex) {

int statusCd = Integer.parseInt(HttpStatus.INTERNAL_SERVER_ERROR.toString());
String statusMessage = messageSource.getMessage("internal.error.status.msg.500", null, Locale.US);

String errorURL = null;
List<APIError> errorInfoList = ex.getApiErrorList();

if (errorInfoList == null || errorInfoList.isEmpty()) {
int errorCode = (ex.getCode() > 0 ? ex.getCode() : 500000);
String errorType = messageSource.getMessage("internal.error.error.type.500", null, Locale.US);
APIError apiError = new APIError(errorCode, errorType, ex.getMessage());
errorInfoList = new ArrayList<APIError>();
errorInfoList.add(apiError);
}

return new APIStatus(statusCd, errorURL, statusMessage, errorInfoList);
}

@ExceptionHandler({APINotFoundException.class})
@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ResponseBody
public APIStatus notFoundError(APINotFoundException ex) {

int statusCd = Integer.parseInt(HttpStatus.NOT_FOUND.toString());
String statusMessage = messageSource.getMessage("not.found.status.msg.404", null, Locale.US);

String errorURL = null;
List<APIError> errorInfoList = ex.getApiErrorList();

if (errorInfoList == null || errorInfoList.isEmpty()) {
int errorCode = (ex.getCode() > 0 ? ex.getCode() : 404000);
String errorType = messageSource.getMessage("not.found.error.type.404", null, Locale.US);
APIError apiError = new APIError(errorCode, errorType, ex.getMessage());
errorInfoList = new ArrayList<APIError>();
errorInfoList.add(apiError);
}

return new APIStatus(statusCd, errorURL, statusMessage, errorInfoList);
}

@ExceptionHandler({APIClientErrorException.class})
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ResponseBody
public APIStatus clientError(APIClientErrorException ex) {

int statusCd = Integer.parseInt(HttpStatus.BAD_REQUEST.toString());
String statusMessage = messageSource.getMessage("bad.request.status.msg.400", null, Locale.US);

String errorURL = null;
List<APIError> errorInfoList = ex.getApiErrorList();

if (errorInfoList == null || errorInfoList.isEmpty()) {
int errorCode = (ex.getCode() > 0 ? ex.getCode() : 400000);
String errorType = messageSource.getMessage("bad.request.error.type.400", null, Locale.US);
APIError apiError = new APIError(errorCode, errorType, ex.getMessage());
errorInfoList = new ArrayList<APIError>();
errorInfoList.add(apiError);
}

return new APIStatus(statusCd, errorURL, statusMessage, errorInfoList);
}

@ExceptionHandler({MethodArgumentNotValidException.class})
@ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY)
@ResponseBody
public APIStatus validationError(MethodArgumentNotValidException ex) {

int statusCd = Integer.parseInt(HttpStatus.UNPROCESSABLE_ENTITY.toString());
String statusMessage = messageSource.getMessage("unprocessable.entity.status.msg.422", null, Locale.US);

String errorURL = null;
int errorCode = 422000;
String errorType = messageSource.getMessage("unprocessable.entity.error.type.422", null, Locale.US);
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
List<com.fbitn.api.errors.FieldError> apiFieldErrors = new ArrayList<com.fbitn.api.errors.FieldError>();

for (FieldError fieldError: fieldErrors) {
String errorMessage = messageSource.getMessage(fieldError, Locale.US);
com.fbitn.api.errors.FieldError apiFieldError = new com.fbitn.api.errors.FieldError(fieldError.getField(), errorMessage);
apiFieldErrors.add(apiFieldError);
}
APIError apiError = new APIError(errorCode, errorType, "Validation Error", apiFieldErrors);
List<APIError> errorInfoList = new ArrayList<APIError>();
errorInfoList.add(apiError);

return new APIStatus(statusCd, errorURL, statusMessage, errorInfoList);
}

@ExceptionHandler({Throwable.class})
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public APIStatus unhandledError(Throwable ex) {



int statusCd = Integer.parseInt(HttpStatus.INTERNAL_SERVER_ERROR.toString());
String statusMessage = messageSource.getMessage("test", null, Locale.US);

String errorURL = null;
int errorCode = 500000;
String errorType = messageSource.getMessage("internal.error.error.type.500", null, Locale.US);
APIError apiError = new APIError(errorCode, errorType, ex.getMessage());
List<APIError> errorInfoList = new ArrayList<APIError>();
errorInfoList.add(apiError);

logger.error("Unhandled Error", ex);
return new APIStatus(statusCd, errorURL, statusMessage, errorInfoList);
}
}

验证类

public class GetPolicyDetails {


@NotNull
@Size(min=7, max=10)
@Pattern(regexp = "^[0-9]*$")
private String policyNbr;

public String getPolicyNbr() {
return policyNbr;
}

public void setPolicyNbr(String policyNbr) {
this.policyNbr = policyNbr;
}
}

应用yml

spring:
application:
name: auto
messages:
basename: messages
encoding: UTF-8
cacheSeconds: -1
endpoints:
shutdown:
enabled: true
default:
locale:en_US

项目结构

  src/main/resources
messages_en.properties

属性。

internal.error.status.msg.500=Internal Error
test=test
internal.error.errror.type.500=Internal Error

bad.request.status.msg.400 = Bad Request
bad.request.error.type.400 = Bad Request

not.found.status.msg.404 = Not Found
not.found.error.type.404 = Not Found

unprocessable.entity.status.msg.422 = Unprocessable Entity
unprocessable.entity.error.type.422 = Unprocessable Entity

最佳答案

发现 @ConditionalOnMissingBean(MessageSource.class) 正在引导过程中使用,但是使用云配置,该资源从未加载,默认的 MessageSource 在没有我的消息的情况下使用。两种修复方法

将此添加到应用程序类以覆盖默认值。

 @Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames( "classpath:messages" );
// if true, the key of the message will be displayed if the key is not
// found, instead of throwing a NoSuchMessageException
messageSource.setUseCodeAsDefaultMessage( true );
messageSource.setDefaultEncoding( "UTF-8" );
// # -1 : never reload, 0 always reload
messageSource.setCacheSeconds( 0 );

return messageSource;
}

或者添加一个工厂来订购meta-inf中的加载首选项..

# Bootstrap components
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration

关于java - Spring验证请求对象错误无法在@ControllerAdvice中找到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com