【发布时间】:2020-01-19 19:53:12
【问题描述】:
我正在使用 Spring Boot 创建几个 REST API,并且正在考虑将异常处理解耦并将其作为外部 jar 文件,然后我可以将其导入我的项目并拥有一个全局异常处理程序逻辑。我为此创建了一个新项目,其中有一个带有 @RestControllerAdvice 注释的类,我将该项目作为依赖项导入到我的 REST API 项目中,我看到异常没有得到处理。
这是我的 REST API 项目中的控制器
package com.xyz.poc.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/hello")
public String hello() throws Exception {
throw new Exception("Error in hello world");
}
}
这是 REST API 的引导类
package com.xyz.poc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.xyz.*"})
public class PocApplication {
public static void main(String[] args) {
SpringApplication.run(PocApplication.class, args);
}
}
下面是 REST API 项目的 build.gradle 文件,其中包含异常处理程序项目的 jar 文件的导入。我手动将 jar 文件复制到 libs 文件夹,这就是它在下面的文件中引用它的原因。
plugins {
id 'org.springframework.boot' version '2.1.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.xyz'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation files('libs/exceptionhandling-0.0.1-SNAPSHOT.jar')
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
task listJars {
configurations.compile.each { File file -> println file.name }
}
下面是@RestControllerAdvice 类,这是与上面提到的不同的项目,并作为依赖项导入到 REST API 项目中
package com.xyz.exception.exceptionhandling;
import com.xyz.exception.exceptionhandling.GenericExceptions.AuthenticationException;
import com.xyz.exception.exceptionhandling.GenericExceptions.ConflictException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
@RestControllerAdvice
public class ControllerExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = { Exception.class })
public ServiceError handleCatchAll(Exception exception, WebRequest req) {
logException(exception);
return new ServiceError(HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = { BindException.class })
public ServiceError handleRequestBindingException(BindException exception) {
logException(exception);
ServiceError errors = new ServiceError(HttpStatus.BAD_REQUEST, exception.getMessage());
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
errors.addField(new ErrorField(error.getField(), error.getDefaultMessage()));
}
return errors;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {
TypeMismatchException.class,
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
IllegalArgumentException.class
})
public ServiceError handleBadRequest(Exception exception) {
logException(exception);
return new ServiceError(HttpStatus.BAD_REQUEST, exception.getMessage());
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(value = { AuthenticationException.class })
public ServiceError handleResponseAuthenticationException(AuthenticationException exception) {
logException(exception);
return new ServiceError(HttpStatus.FORBIDDEN, exception.getMessage());
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(value = { NoHandlerFoundException.class })
public ServiceError handleNoHandlerFoundException(NoHandlerFoundException exception) {
logException(exception);
return new ServiceError(HttpStatus.NOT_FOUND, exception.getMessage());
}
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(value = { ConflictException.class })
public ServiceError handleConflictException(ConflictException exception) {
logException(exception);
return new ServiceError(HttpStatus.CONFLICT, exception.getMessage());
}
private void logException(Throwable exception) {
LOGGER.error("An error occurred: " + exception.getMessage());
LOGGER.debug("An error occurred", exception);
}
}
这是我的异常处理项目中的引导程序
package com.xyz.exception.exceptionhandling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExceptionhandlingApplication {
public static void main(String[] args) {
SpringApplication.run(ExceptionhandlingApplication.class, args);
}
}
【问题讨论】:
-
我从来没有使用
*扫描包。您是否尝试过使用@SpringBootApplication(scanBasePackages = {"com.xyz"}) -
试试
@ComponentScan(basePackages = {"com.example.from.jar"} -
@PasupathiRajamanickam 我尝试不使用通配符,但遇到了同样的问题
-
@KamilW 你提到的方式其实和我做的一样,反正我试过你的方式但还是一样的问题
-
你是如何导入第二个 jar 的?你确定你在类路径中有它吗?
标签: java spring spring-boot