I have written a very simple gradle spring boot project. But non of my exception handling is working.
Tried handling at @Controller level and also at global via @ControllerAdvice, but both doesn't seems to work.
Could it be because its a gradle project so its not working ?
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 Advice 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'
}
Application 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
CodePudding user response:
Just looked at your code & issue is you have wrong annotation @org.springframework.stereotype.Controller
for Controller
.
Please note this is rest call & hence you have to use org.springframework.web.bind.annotation.RestController
for 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";
}
}
Once you change this & execute
curl http://localhost:8080/test
you will get :
Test NPE