【发布时间】:2015-08-03 23:21:10
【问题描述】:
解决
在rest api应用程序中,异常处理方法的返回类型应该是ResponseEntity或者用@ResponseBody注释方法,这样spring boot就可以进行http序列化。
更新
入门类:
@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
@EnableConfigurationProperties
@EnableTransactionManagement//TODO remove this line if not needed
public class Application extends SpringBootServletInitializer{
private static Class<Application> applicationClass= Application.class;
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(applicationClass);
}
}
我在 Spring Boot Starter Web 中使用 @ControllerAdvice 处理全局异常处理,但遇到了一个奇怪的问题。
当我按照 Spring 官方文档 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc 的指南来处理全局异常时,只需添加一个带有 @ControllerAdivce 注释的处理程序类。但是,当我测试它时,抛出RunTimeException 时不会调用异常处理方法。
这是我的代码:
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public RestEntity handleException(HttpServletRequest req, RuntimeException ex) {
RestEntity restEntity=new RestEntity();
Message message=new Message();
message.setCode(1000);
message.setMessage("Something wrong with the server");
restEntity.setMessage(message);
return restEntity;
}
}
我在其他控制器中使用@ExceptionHandler 注释的方法来处理每个控制器中的特定异常,同时将未解决的异常留给GlobalDefaultExceptionHandler。
事实证明它不起作用。我在这里错过了什么吗??
现在,作为一种解决方法,我只需在GlobalDefaultExceptionHandler 上添加@RestControoler,它就可以正常工作。我不知道为什么...
有人可以帮忙吗?
【问题讨论】:
-
发布一些配置。
-
M. Deinum我没有太多配置,只是一个application.properties,里面只包含一些数据库配置、redis配置和日志配置。与异常处理逻辑无关
-
至少添加一些东西,一个入门类等。
@ControllerAdvice是一个@Component,所以它应该被检测到,所以你必须在某个地方禁用正确的组件扫描。 -
M. Deinum 我如上所述添加了入门类。但是,我想我自己已经弄清楚了...我尝试将异常处理方法的返回类型
handleException更改为ResponseEntity<RestEntity>,它再次起作用了... Springboot必须要包装异常处理程序的返回类型方法,没有ResponseEntity,springboot只是忽略返回类型,给出默认的响应对象结构,带有时间戳、错误信息、url等... -
您也可以添加
@ResponseBody,因为这正是您想要的。
标签: java spring spring-mvc spring-boot