【问题标题】:spring boot starter web @ControllerAdvice annotation is not work without having @RestController annotationspring boot starter web @ControllerAdvice 注释在没有 @RestController 注释的情况下不起作用
【发布时间】: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&lt;RestEntity&gt;,它再次起作用了... Springboot必须要包装异常处理程序的返回类型方法,没有ResponseEntity,springboot只是忽略返回类型,给出默认的响应对象结构,带有时间戳、错误信息、url等...
  • 您也可以添加@ResponseBody,因为这正是您想要的。

标签: java spring spring-mvc spring-boot


【解决方案1】:

我实际上不得不从我的主应用程序文件中删除 @EnableWebMvc。

这里是我的工作配置:

@SpringBootApplication
@ComponentScan(basePackages = {
....
})
public class Application extends SpringBootServletInitializer { ... }

和 ControllerAdvice:

@ControllerAdvice
public class ErrorHandlingController { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2019-09-18
    • 2019-12-18
    • 1970-01-01
    • 2022-11-24
    • 2015-09-01
    相关资源
    最近更新 更多