提问者:小点点

@控制建议或@ExceptionHandler都不适用于gradle项目


我已经写了一个非常简单的gradle Spring启动项目。但是我的异常处理不起作用。

尝试在@Controller级别处理,也尝试通过@ControlllerAdac在全局处理,但两者似乎都不起作用。

会不会是因为它是一个gradle项目,所以它不起作用?

控制器类

@org.springframework.stereotype.Controller
public class Controller {

    @GetMapping(value="/test")
    public String testController(){
//        return "Test me";
        throw new NullPointerException();
    }

    @ExceptionHandler(value=NullPointerException.class)
    public String handleNPE(Exception e){
        return "Test NPE";
    }

}

控制器建议类

package MyController;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class advice {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleNPE(Exception e){
        return "Caught by advisor";
    }
}

Also tried importing ControllerAdvice class explicitly but that doesn't help as well.

build. gradle

    id 'org.springframework.boot' version '2.7.2'
    id 'io.spring.dependency-management' version '1.0.12.RELEASE'
    id 'java'
    id 'org.springframework.experimental.aot' version '0.12.1'
}

应用类

package com.example.springdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import(MyController.advice.class)
public class SpringDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }

}


}```


github repo - https://github.com/Akashtyagi/SpringBootProject

共1个答案

匿名用户

刚看了你的代码

请注意这是Rest电话

@org.springframework.web.bind.annotation.RestController
public class Controller {

    @GetMapping(value="/test")
    public String testController(){
//        return "Test me";
        throw new NullPointerException();
    }

    @ExceptionHandler(value=NullPointerException.class)
    public String handleNPE(Exception e){
        return "Test NPE";
    }

}

一旦你改变了这个

curl http://localhost:8080/test

您将获得:

测试NPE