簡體   English   中英

@ControllerAdvice 或 @ExceptionHandler 都不適用於 gradle 項目

[英]@ControllerAdvice or @ExceptionHandler both not working on gradle project

我寫了一個非常簡單的 gradle spring 引導項目。 但是我的異常處理都不起作用。

嘗試在@Controller 級別處理以及通過@ControllerAdvice 在全局處理,但兩者似乎都不起作用。

可能是因為它是一個 gradle 項目所以它不起作用?

Controller class

@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";
    }

}

Controller 建議 class

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'
}

應用 class

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

只是看了你的代碼&問題是你有錯誤的注釋@org.springframework.stereotype.ControllerController

請注意這是 rest 調用,因此您必須使用org.springframework.web.bind.annotation.RestController為 controller。

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM