gpt4 book ai didi

java - 在不同的 jar 文件中使用 @RestControllerAdvice 不会捕获异常

转载 作者:行者123 更新时间:2023-12-02 00:32:38 26 4
gpt4 key购买 nike

我正在使用 Spring Boot 创建几个 REST API,并正在考虑解耦异常处理并将其作为外部 jar 文件,然后我可以将其导入到我的项目中并拥有一个全局异常处理程序逻辑。我为此创建了一个新项目,其中有一个带有 @RestControllerAdvice 注释的类,并且我将该项目作为依赖项导入到我的 REST API 项目中,我发现该异常未得到处理。

这是我的 REST API 项目中的 Controller

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);
}
}

这是我的异常处理项目中的 Bootstrap

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);
}

}

最佳答案

替换

implementation files('libs/exceptionhandling-0.0.1-SNAPSHOT.jar')

compile files('libs/exceptionhandling-0.0.1-SNAPSHOT.jar')

关于java - 在不同的 jar 文件中使用 @RestControllerAdvice 不会捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57999840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com