- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
所有其他错误都通过 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/
我可以定义一个 Spring ControllerAdvice,它由使用自定义注解的 Controller 子集有选择地使用: @RestController @UseAdviceA @Request
这是 web 入口点的主 Controller @Controller @RequestMapping("/webapp") public class WebAppController { @Requ
我有一个 Spring 4 应用程序,其中包含多个用 @Order(someValue) 注释的 ControllerAdvices。此外,我在我的一个外部库中发现了一个 ControllerAdvi
实现前的准备工作 @ControllerAdvice注解的简单介绍 @ControllerAdvice注解作用是给Controller控制器添加统一的操作或处理。 对于@ControllerAdvic
我一直在关注一些有关使用 Spring 框架进行错误处理的教程。我的handleNullPointer方法确实捕获了空指针异常。但是,我想知道该方法之后返回到哪里,因为我想在前端(网页)上显示错误的一
有没有办法从 @ControllerAdvice 获得控制权的地方获取类。 即:如果 PersonController 的执行正在进行,并且我收到一些错误,由于控制权转移到 @ControllerAd
我有一个用 @ControllerAdvice 注释的类,为我的 api 提供了一些中央异常处理。它处理的异常之一是 MethodArgumentNotValidException,当用 @Valid
我想将响应正文设置为异常的错误消息: @ControllerAdvice public class RestResponseEntityExceptionHandler extends Respons
实际上,我在一个单独的项目中使用 @ControllerAdvice 为我的 Sprint 启动项目编写了一个全局 ExceptionHandling,现在我想从另一个项目调用它,但似乎它不起作用,因
我有一个 REST 服务,我需要使用自定义 json 响应发送适当的状态代码,这解释了错误的原因。 我有@Controller类,它公开了一个服务/test,在访问该服务时,我抛出了一个自定义异常(扩
我已经浏览了所有相关的帖子,但我的@ControllerAdvice似乎没有处理从 Controller 类抛出的自定义异常。但是@Controller类中的@ExceptionHandler确实处理
我正在开发一个 Spring MVC/Webflow 应用程序(版本 3.2)并尝试让异常处理工作,我可以在其中将自定义异常消息输出到日志文件和 error.jsp。我遇到的问题是异常处理程序没有被解
我正在为 Spring MVC 中的异常处理开发示例演示应用程序。我正在尝试使用@ControllerAdvice 进行异常处理 我按照 this 中描述的步骤进行操作链接。 但是当我运行我的应用程序
我有以下 Controller 类 package com.java.rest.controllers; @Controller @RequestMapping("/api") public clas
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@Req
我有 SimpleMappingExceptionResolver像这样配置。 @Bean(name = "simpleMappingExceptionResolver") public Simple
我不知道为什么,但 @ControllerAdvice覆盖在 Exception 处定义的响应代码级别使用 @ResponseStatus注解。 异常(exception) : @ResponseSt
我制作了一个用于监听异常的通用项目并使用 @ControllerAdvice与 @ExceptionHandler @ControllerAdvice(annotations = RestContro
在我的 REST 服务应用程序中,我计划创建一个 @ControllerAdvice捕获 Controller 抛出的异常并返回 ResponseEntity 的类对象根据错误类型。 但我已经有一个
@RestControllerAdvice 和 @ControllerAdvice 之间的主要区别是什么? 我们是否应该始终将 @RestControllerAdvice 用于休息服务和 @Contr
我是一名优秀的程序员,十分优秀!