簡體   English   中英

未達到Spring MVC中的異常處理

[英]Exception Handling in Spring MVC not reached

我以這種方式聲明了一個全局異常處理程序:

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

}

MissingMandatoryPropertyException簡單擴展了RuntimeException,這是我從Spring Boot控制器拋出異常的方式:

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

因此,我期望的是GlobalDefaultExceptionHandler攔截引發的異常,但是由於某種原因,它沒有發生。

我編寫了這個junit來測試異常行為:

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

}

}

一切似乎都已正確配置,但似乎Spring Boot不知道必須使用GlobalDefaultExceptionHandler來處理異常。 相同的實現適用於tomcat下的spring mvc應用程序,但不適用於spring boot。

更新
控制器是@RestController

有什么線索嗎?

要對其進行測試,您應該將ControllerAdvice添加到mockMvc如下所示:

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

先前的答案是正確的。如果您不想顯式定義它,則可以在@ControllerAdvice中提供基本包。

像這樣

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

暫無
暫無

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

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