Andrea Girardi
Andrea Girardi

Reputation: 4427

Exception Handling in Spring MVC not reached

I declared a global exception handler in this way:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = MissingMandatoryPropertyException.class)
    public @ResponseBody ResponseEntity<String> missingMandatoryPropertyException(HttpServletRequest req, MissingMandatoryPropertyException exception) throws Exception {   
        return new ResponseEntity<String>("Missing mandatory parameter: " + exception.getMessage(), HttpStatus.BAD_REQUEST);
    }

}

The MissingMandatoryPropertyException simple extend the RuntimeException and this is how I throw the exception from my spring boot controller:

    if (userId == null){
        throw new MissingMandatoryPropertyException("userId");
    }

So, what I'm expecting is that the GlobalDefaultExceptionHandler intercept the exception raised but, for some reason it's not happening.

I wrote this junit to test the exception behavior:

@WebAppConfiguration
@SpringApplicationConfiguration(SpringRunner.class)
@TestPropertySource(locations="classpath:/config/local/env.config")
@SuppressWarnings("unused")
public class ExceptionControllerTest {

protected static final Logger logger = LoggerFactory.getLogger(ExceptionControllerTest.class);

protected MockMvc mockPHRMvc;

@Before
public void setup() {
    this.mockPHRMvc = MockMvcBuilders.standaloneSetup(new PhrController()).build();
}

@Test public void testGetPhr_missingUserID() {

    try {                   
        MvcResult result = mockPHRMvc.perform(get("/api/1.0/phr")).andExpect(status().is(HttpStatus.BAD_REQUEST.value())).andReturn();      
    } catch (Exception ex) {
        logger.error("Exception(): ", ex);
    }

}

}

Everything seems configured correctly but, it seems that spring boot doesn't know that has to use the GlobalDefaultExceptionHandler for the exception. Same implementation worked with a spring mvc application under tomcat but not with spring boot.

Updated
the controller is @RestController

Any clue?

Upvotes: 1

Views: 923

Answers (2)

Amit Jambotkar
Amit Jambotkar

Reputation: 92

Previous answer is right.. If you dont want to define it explicitly then you can provide base package in @ControllerAdvice

like this

@ControllerAdvice(basePackages = {"com.XYZ.abc"})

Upvotes: 3

Orest
Orest

Reputation: 6748

To test it you should add ControllerAdvice to mockMvc like:

@Before
public void setup() {
    this.mockPHRMvc = MockMvcBuilders.standaloneSetup(new PhrController()).setControllerAdvice(new GlobalDefaultExceptionHandler()).build();
}

Upvotes: 3

Related Questions