在其他jar文件中使用@RestControllerAdvice不能捕获异常

时间:2019-09-18 19:48:16

标签: java spring spring-boot

我正在使用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);
    }

}

1 个答案:

答案 0 :(得分:0)

替换

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

使用

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