我制作了一个用于监听 Exception 的通用项目,并将@ControllerAdvice
与@ExceptionHandler
@ControllerAdvice(annotations = RestController.class)
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({Exception.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<ErrorResponse> notFound(Exception ex) {
return new ResponseEntity<>(
new ErrorResponse(ex.getMessage(), 404, "My Custom Message"), HttpStatus.NOT_FOUND);
}
}
没有任何@SpringBootApplication
和主要方法添加为依赖关系到我的另一个项目。我的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>spring-commons-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-commons-rest</name>
<description>for Listening Exceptions</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
将其依赖项和@ComponentScan
添加到另一个项目后,但不能作为响应自定义错误的异常处理。感谢您的帮助。
答案 0 :(得分:0)
我发现这与使用@ComponentScan
无关,而与使用@Import
一样,它可以很好地工作。但是如果有人有更好的解决方案或指导方针,我将不胜感激。